Summary of Linked list (second article)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.