1 /*************************************************************************2 > File name:35_firstcommonnode.cpp3 > Author:juntaran4 > Mail: [email protected]5 > Created time:2016 September 02 Friday 20:52 28 seconds6 ************************************************************************/7 8#include <stdio.h>9#include <malloc.h>Ten One //linked list structure body A structListNode - { - intVal; the structlistnode*Next; - }; - - //sequential output linked list + voidPrintlist (listnode*head) - { + if(Head = =NULL) A return; atlistnode* temp =head; -printf"printlist:\n"); - while(Temp! =NULL) - { -printf"%d", temp->val); -temp = temp->Next; in } -printf"\ n"); to } + - //Get the chain table length the intGetlistlength (listnode*head) * { $ intLength =0;Panax Notoginsenglistnode* p =head; - while(P) the { +Length + +; Ap = p->Next; the } + returnlength; - } $ $ //look for the first common knot. -listnode* Findfirstcommonnode (listnode* head1, listnode*head2) - { the intLength1 =getlistlength (head1); - intLength2 =getlistlength (head2);Wuyi thelistnode*longlist; -listnode*shortList; Wu intdiff; - About if(Length1 >=length2) $ { -longlist =Head1; -ShortList =head2; -diff = length1-length2; A } + Else the { -longlist =head2; $ShortList =Head1; thediff = length2-length1; the } the the for(inti =0; I < diff; ++i) -longlist = longlist->Next; in the while(Longlist && shortList && shortlist!=longlist) the { Aboutlonglist = longlist->Next; theShortList = shortlist->Next; the } the + if(Longlist = =NULL) -printf"Not find\n"); the ElseBayiprintf"Find%d\n", longlist->val); the the returnlonglist; - } - the intMain () the { the //test linked list structure thelistnode* head1 = (listnode*)malloc(sizeof(ListNode)); -Head1->val =1; thelistnode* P1 =Head1; the for(inti =0; I <4; ++i) the {94listnode* q1 = (listnode*)malloc(sizeof(ListNode)); theQ1->val = i +2; theP1->next =Q1; theP1 =Q1;98 } AboutP1->next =NULL; - 101 102listnode* head2 = (listnode*)malloc(sizeof(ListNode));103Head2->val =6;104listnode* P2 =head2; the for(inti =0; I <4; ++i)106 {107listnode* q2 = (listnode*)malloc(sizeof(ListNode));108Q2->val = i +7;109P2->next =Q2; theP2 =Q2;111 } theP2->next =NULL;113 theP1->next = head2->next->Next; the the printlist (head1);117 printlist (head2);118 119 Findfirstcommonnode (Head1, head2); -}
Sword Offer35 Two lists the first public node of the list.