1 #include<iostream> 2 using namespace std; 3 4 typedef struct Node{ 5 int data; 6 struct Node *next; 7 }Node; 8 9 //头插法建立链表 10 Node *createListFromHead(int a[], int n){ 11 Node *A = new Node(); 12 A->next = NULL; 13 for(int i=0; i<n; i++){ 14 Node *p = new Node(); 15 p->data = a[i]; 16 p->next = A->next; 17 A->next = p; 18 } 19 return A; 20 } 21 22 //尾插法建立链表 23 Node *createListFromEnd(int a[], int n){ 24 Node *A = new Node(); 25 A->next = NULL; 26 Node *p = A; 27 for(int i=0; i<n; i++){ 28 Node * q = new Node(); 29 q->next = NULL; 30 q->data = a[i]; 31 p->next = q; 32 p = q; 33 } 34 return A; 35 } 36 37 void show(Node *List){ 38 Node *p = List->next; 39 while(p){ 40 cout<<p->data<<endl; 41 p = p->next; 42 } 43 } 44 45 46 //求两个链表的差 47 void uni(Node *A, Node *B){ 48 Node *Apre = A, *Anow = A->next; 49 Node *Bnow = B->next; 50 while(Anow && Bnow){ 51 while(Bnow && Bnow->data < Anow->data){ 52 Bnow = Bnow->next; 53 } 54 if(Bnow && Bnow->data != Anow->data){ 55 Apre->next = Anow->next; 56 57 }else{ 58 Apre = Apre->next; 59 } 60 Anow = Anow->next; 61 62 } 63 if(Anow){ 64 Apre->next = NULL; 65 } 66 } 67 68 int main(){ 69 int a[]={1,2,3,4,5,6,7,8,9}; 70 int b[]={1,3,5,6,9}; 71 // Node *A = createListFromHead(a, 9); 72 Node *A = createListFromEnd(a, 9); 73 Node *B = createListFromEnd(b,5); 74 uni(A, B); 75 show(A); 76 // cout<<endl; 77 // show(B); 78 }
原文地址:https://www.cnblogs.com/zhishoumuguinian/p/11755180.html
时间: 2024-10-09 09:56:09