zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[LeetCode] Intersection of Two Linked Lists

LeetCode of two Linked lists intersection
2023-09-14 09:01:04 时间

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

begin to intersect at node c1.


解题思路
首先把两个链表的所有非空结点入栈,然后比较栈顶元素并出栈,直到一个栈为空或者栈顶元素不相等,此时上一次比较的结点即为相交结点。
/*************************************************************

 * @Author : 楚兴

 * @Date : 2015/2/8 13:33

 * @Status : Accepted

 * @Runtime : 76 ms

*************************************************************/

#include vector 

#include iostream 

#include stack 

using namespace std;

struct ListNode {

 int val;

 ListNode *next;

 ListNode(int x) : val(x), next(NULL) {}

class Solution {

public:

 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

 stack ListNode* stack1;

 stack ListNode* stack2;

 ListNode* pa = headA;

 ListNode* pb = headB;

 while(pa)

 stack1.push(pa);

 pa = pa- next;

 while(pb)

 stack2.push(pb);

 pb = pb- next;

 ListNode* temp = NULL;

 while (!stack1.empty() !stack2.empty())

 if (stack1.top()- val == stack2.top()- val)

 temp = stack1.top();

 stack1.pop();

 stack2.pop();

 else

 return temp;

 return temp;

void addListNode(ListNode* head, int i)

 ListNode* h = head;

 while(h- next != NULL)

 h = h- next;

 ListNode* temp = new ListNode(i);

 h- next = temp;

//void print(ListNode* head)

// ListNode* temp = head;

// while(temp)

// cout temp- val endl;

// temp = temp- next;

int main()

 Solution s;

 ListNode* headA = new ListNode(0);

 addListNode(headA, 1);

 addListNode(headA, 2);

 addListNode(headA, 1);

 addListNode(headA, 2);

 addListNode(headA, 3);

 ListNode* headB = new ListNode(0);

 addListNode(headB, 1);

 addListNode(headB, 2);

 addListNode(headB, 3);

 addListNode(headB, 1);

 addListNode(headB, 2);

 addListNode(headB, 3);

 ListNode* p = s.getIntersectionNode(headA, headB);

 cout p- val endl;

 system("pause");

}

LeetCode 328. Odd Even Linked List 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
LeetCode 160: 相交链表 Intersection of Two Linked Lists 爱写Bug(ID:iCodeBugs) 编写一个程序,找到两个单链表相交的起始节点。 Write a program to find the node at which the intersection of two singly linked lists begins. 如下面的两个链表: 在节点 c1 开始相交。
题目大意:对结构体进行排序 分析:建立结构体数组,按照从首地址开始的顺序(直到-1)遍历一遍整个链表,
Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to