判断两个链表是否相交;查找两个链表的第一个公共节点;头插法建链表(补充)

问题一:(引用编程之美)如果两个链表相交,则尾节点一定是公共的

问题二:

头插法建链表(补充,头指针而非投节点)

 1 node* createList(int array[],int n){
 2     node* head=NULL;
 3     node* temp=NULL;
 4     for(int i=n-1;i>=0;i--){
 5         temp=new node;
 6         temp->data=array[i];
 7         temp->next=head;
 8         head=temp;
 9     }
10     return head;
11 }

查找两个链表的第一个公共节点

 1 int listLength(node* list){
 2     int length=0;
 3     while(list!=NULL){
 4         length++;
 5         list=list->next;
 6     }
 7     return length;
 8 }
 9 //
10 node* firstComNode(node* list1,node* list2){
11     int n1=listLength(list1);
12     int n2=listLength(list2);
13     //定义指针pLong,pShort,分别指向长列表和短列表
14     node* pLong=list1;
15     node* pShort=list2;
16     if(n1<n2){
17         pLong=list2;
18         pShort=list1;
19     }
20     //将指向长列表的指针前移一定距离d
21     int d=((n1-n2)>0)?(n1-n2):(n2-n1);
22     while(d--){
23         pLong=pLong->next;    
24     }
25     //两个指针同时向尾部遍历,查找第一个相同的节点
26     while(pLong!=NULL && pLong!=pShort){
27         pLong=pLong->next;
28         pShort=pShort->next;
29     }
30     return pLong;
31 }

 

posted @ 2014-09-16 15:15  liuzhiminxd  阅读(222)  评论(0编辑  收藏  举报