1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| #include<iostream> #include <stdlib.h> #include <string.h> using namespace std;
typedef struct Node//结点 { int data;//数据域 struct Node *next;//指针域 }NODE, *PNODE;//NODE等价于struct Student st||PNODE等价于struct Node *next
PNODE InputStudent(void) { int len;//学生的人数 NODE stu; PNODE pHead = (PNODE)malloc(sizeof(NODE));//定义一个头结点并且为头结点分配内存 if(NULL == pHead) //判断内存是否为空 { printf("内存分配失败,程序终止!\n"); exit(-1); } PNODE pTail = pHead;//定义一个指向头结点的指针 pTail->next = NULL;//清空指针域 printf("请输入个数:"); scanf("%d",&len); for(int i=0; i<len; i++) { printf("请输入第%d个:\n", i+1); cin>>stu.data;
PNODE pNew = (PNODE)malloc(sizeof(NODE)); //为新节点分配内存 if(NULL == pNew) //判断内存是否为空 { printf("内存分配失败,程序终止!\n"); exit(-1); }
pNew->data = stu.data;//初始化结点的数据域 pTail->next = pNew;//将新结点挂到老结点后 pNew->next = NULL;//清空新结点的指针域 pTail = pNew;//将pTail移到新结点上 } return pHead; }
void OutputStudent(PNODE pHead)//输出学生信息 { PNODE p = pHead->next;//定义一个指针用于遍历学生信息 printf("\n数据如下:\n"); while(NULL != p) { printf("%d ", p->data); p = p->next; } }
void MergerList(PNODE &LA,PNODE &LB,PNODE &LC){ OutputStudent(LA); OutputStudent(LB); NODE *pa,*pb,*pc; // pa指向LA,pb指向LB,pc指向LC; pa=LA->next; pb=LB->next; LC=LA; pc=LC; //pc指向LC头指针 while(pa&&pb){ if(pa->data<=pb->data){ pc->next=pa; pc=pa; //更新pc的指向 pa=pa->next; } else{ pc->next=pb; pc=pb; pb=pb->next; } } pc->next=pa?pa:pb; delete LB; }
PNODE GuiblingList(PNODE A,PNODE B){ OutputStudent(A); OutputStudent(B); NODE *p,*q,*r; // p指向A,q指向B; q=A; p=B->next; while(p){ while((q->next)&&(q->next->data<p->data)){ q=q->next; }
r=p; p=p->next; r->next=q->next; q->next=r; } return A; }
int main(){ PNODE LA= InputStudent(); PNODE LB= InputStudent(); PNODE LC; LC=GuiblingList(LA,LB); OutputStudent(LC); // MergerList(LA,LB,LC); // OutputStudent(LC); return 0; }
|