The first part of the problem is the operation of a list of cases, this article mainly on a number of linked list of some problems
(1) Merging two lists that have been sorted
//l1, L2 Two pointers constantly moving back ListNode*mergesortedlists (ListNode *l1, ListNode *L2) {ListNode Newhead (0), *pos = &Newhead; while(L1 | |L2) { if(!L1)return(Pos->next =L2, Newhead.next); if(!L2)return(Pos->next =L1, Newhead.next); (L1->val < L2->val)? (pos = Pos->next = L1, L1 = l1->next): (pos = Pos->next = L2, L2 = l2->next); } returnNewhead.next; }
(2) Determine if two non-linked lists Intersect
// to determine whether the two linked lists Intersect, just determine whether the last node of the two list is the same. bool ismeetlist (ListNode *phead1, ListNode *pHead2) { if(!phead1 | |!phead2) Returnfalse; *POS1 = pHead1, *pos2 = pHead2; while (pos1->Next) { = pos1->next; } while (pos2->Next) { = pos2->next; } return pos1 = = pos2;}
(3) Finding the first intersection point of two non-linked lists
//find the first intersection point of two lists, first traverse two linked list, get two linked list length, for example L1, L2//then move the long list (for example, L1>L2) and move the L1-L2 step so that the number of nodes remaining on both sides is equal.//and then go backwards, the first point of meeting is the answer .ListNode *getfirstmeet (ListNode *phead1, ListNode *pHead2) { if(!phead1 | |!phead2)returnNULL; ListNode*POS1 = pHead1, *pos2 =pHead2; intL1 =0, L2 =0; while(pos1->next) {L1++; POS1= pos1->Next; } while(pos2->next) {L2++; Pos2= pos2->Next; } if(pos1! = Pos2)returnNULL; POS1= L1 > L2?phead1:phead2; Pos2= L1 > L2?Phead2:phead1; intCount = L1 > L2? L1-L2:L2-L1; while(count-->0) {pos1= pos1->Next; } while(Pos1 &&Pos2) { if(pos1 = = Pos2)returnpos1; POS1= pos1->Next; Pos2= pos2->Next; } }
Summary of Linked list (second article)