Sword refers to the first common node of the offer--037-two list

Source: Internet
Author: User

Link

New Ket OJ: First common node of two lists

Nine degrees oj:http://ac.jobdu.com/problem.php?pid=1505

GitHub code: 037-The first common node of a two-linked list

Csdn: Sword refers to the first common node of a list of two offer–037-

New Ket OJ Nine degrees OJ csdn GitHub Code
037-The first common node of a two-linked list 1505-The first common node of a two-linked list Sword refers to the first common node of the offer–037-two list 037-The first common node of a two-linked list
Test instructions

Title Description

Enter two linked lists to find their first common node.

Methods of violence

The simplest and most straightforward approach is that for each node in the first list, we determine in turn whether it is the public node of the second linked list

#include <iostream>using namespace STD;//DEBUG Switch#define __tmain Main#ifdef __tmain#define DEBUG Cout#else#define DEBUG 0 && cout#endif //__tmain #ifdef __tmainstructlistnode{ Public:intValstructListNode *next;};#endifclasssolution{ Public: listnode* Findfirstcommonnode (ListNode *lefthead, ListNode *righthead) {ListNode *left = NULL; ListNode *right = NULL;//Loop Each node of the first linked list         for(left = Lefthead;            Left! = NULL; left = left->next) {Debug <<endl <<left->val <<" : ";//To determine that it is not in the second linked list in turn             for(right = Righthead;                Right! = NULL; right = Right->next) {Debug <<right->val <<", ";if(left = right) { Break; }                            }if(left = right) { Break; }        }returnLeft }};int__tmain () {ListNode common[2]; common[0].val =6; common[0].next = &common[1]; common[1].val =7; common[1].next = NULL; ListNode left[3]; left[0].val =1; left[0].next = &left[1]; left[1].val =2; left[1].next = &left[2]; left[2].val =3; left[2].next = &common[0]; ListNode right[2]; right[0].val =4; right[0].next = &right[1]; right[1].val =5; right[1].next = &common[0];    Solution Solu; ListNode *node = Solu. Findfirstcommonnode (left, right); while(Node! = NULL) {Debug <<node->val <<" ";    node = node->next; } Debug <<endl;return 0;}
Right-aligned two linked lists

If two linked lists have common nodes, their shape must be a Y-glyph.

Long list go first, achieve right alignment

Assuming that the two lists are of equal length, we can iterate through the two linked lists and find the common nodes. Now there are two linked lists, we can first separate the length of the difference N, and then traverse the long list of n nodes, and then iterate through the two linked lists.

classsolution{ Public: listnode* Findfirstcommonnode (ListNode *lefthead, ListNode *righthead) {ListNode *left = LeftHead; ListNode *right = Righthead;intLeftlength =0;intRightlength =0;/// first calculate the length of two linked listsLeftlength = Getlistlength (left); Rightlength = Getlistlength (right);/// align two linked lists        intLength =0;if(Leftlength < Rightlength) {//Right chain table lengthlength = Rightlength-leftlength; while(Right! = NULL && length >0) {right = right->next;            length--; }        }Else{//Zolin longlength = Leftlength-rightlength; while(Left! = NULL && length >0) {left = left->next;            length--; }        }///Two pointers synchronized move to find common nodes         while(left! = null && right! = null) {if(left = right) { Break;            } left = left->next;        right = right->next; }return(left = right)? left:null); }intGetlistlength (ListNode *head) {ListNode *node = head;intLength =0; while(Node! = NULL)            {length++;        node = node->next; }returnLength }};
Align two lists together for right alignment

In front of that idea, the long list first goes a length difference, so that the two linked list is right-aligned, but in this way, we need to sweep the table multiple times, because the list must be scanned to get its length

But there is no way to align two lists without having to scan them multiple times.

We can stitch together two linked lists to achieve their

Left:left->right

>

Right:right->left

In this way our list becomes the length of the m + n Span style= "Display:inline-block; width:0px; Height:2.349em; " > The two linked lists, while the public ones are at the end, and are aligned

classsolution{ Public: listnode* Findfirstcommonnode (ListNode *lefthead, ListNode *righthead) {ListNode *left= leftHead;        ListNode *right = Righthead; Debug << (left = = NULL?-1: Left->val) <<", "; Debug << (right = = NULL?-1: Right->val) <<endl; while(Left! = right)            {left = (left = = NULL? righthead:left->next);            right = (right = = NULL? lefthead:right->next); Debug << (left = = NULL?-1: Left->val) <<", "; Debug << (right = = NULL?-1: Right->val) <<endl; }returnLeft }};
The last-in-first-out of the stack enables right alignment

Because the stack is LIFO, so we put two linked lists into the stack, then the stack top element must be the last element. Thus two linked lists are right-aligned, two stacks are ejected synchronously, and when the nodes at the top of the two stack are not the same, that is the first node to begin merging

classsolution{ Public: listnode* Findfirstcommonnode (ListNode *lefthead, ListNode *righthead) {ListNode *left = LeftHead; ListNode *right = Righthead; Stack<listnode *>Leftstack; Stack<listnode *>Rightstack;/// nodes into the stack sequentially.         while(Left! = NULL) {//debug <<left->val <<endl;Leftstack.push (left);        left = left->next; } while(Right! = NULL) {//debug <<right->val <<endl;Rightstack.push (right);        right = right->next; }/// start synchronizing popup elements         while(Leftstack.empty ()! =true&& rightstack.empty ()! =true) {left = Leftstack.top ();            right = Rightstack.top (); Debug <<left->val <<", "<<right->val <<endl;/// A different element is the previous node of the merge            if(Left! = right) { Break;            } leftstack.pop ();        Rightstack.pop (); }/// the next node of a different element is the joint node .        if(Left! = right) {returnleft->next; }Else{returnNULL; }    }};
Find nodes with an efficient data structure

Of course there are other ideas that we can use to find efficient data structures such as hash or map

>

The first linked list is inserted first, then the node of the second list is not in map, so it can find the first common node.

Using Unordered_map, this template class is based on the hash table, which is faster than the map and HashMap.

classsolution{ Public: listnode* Findfirstcommonnode (ListNode *lefthead, ListNode *righthead) { unordered_map<listnode*, bool>Umap; listnode* left = Lefthead; while(Left! = NULL) {Umap.insert (Make_pair (left,1));        left = left->next; } listnode* right = Righthead; while(right) {if(Umap.count (right) >0)            {returnRight        } right = right->next; }returnNULL; }};

Sword refers to the first common node of the offer--037-two list

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.