题目描述:编写一个程序,找到两个单链表相交的起始节点。
1.暴力求解:一个个进行对比,找到第一个相等的节点就是交点
ps:效率低
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL || headB == NULL)
{
return NULL;
}
while(headA != NULL)
{
ListNode *p = headB; //p进行位移对比
while(p != NULL)
{
if(p == headA)
{
return p;
}
else
{
p = p->next;
}
}
headA = headA->next;
}
return NULL;
}
};
2.将两个链表长度对齐开始对比:链表相交后,后面节点一致;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL || headB == NULL)
{
return NULL;
}
int len1 = 0;
int len2 = 0;
ListNode *p = headA;
ListNode *q = headB;
while(p->next != NULL)
{
p = p->next;
len1++;
}
while(q->next != NULL)
{
q = q->next;
len2++;
}
if(p != q) return NULL; //p、q指向链表尾部
while(len1 != len2)
{
if(len1 > len2)
{
headA = headA->next;
len1--;
}
if(len1 < len2)
{
headB = headB->next;
len2--;
}
}
while(headA != headB)
{
headA = headA->next;
headB = headB->next;
}
return headA;
}
};
3.结合栈进行求解:将两个链表分别进行压栈操作,之后进行对比出栈,当元素一致时就不断出出出,不一致就停止出栈操作,之后开始判断两个栈是否为空的情况,分别讨论应该返回哪个元素!!情况太多了,提交了7次才通过
[777777777777777777酱(•̀ᴗ•́)و ̑̑] 7的意志
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL || headB == NULL)
{
return NULL;
}
stack<ListNode*> st1;
stack<ListNode*> st2;
ListNode *p = headA;
ListNode *q = headB;
while(p != NULL)
{
st1.push(p);
p = p->next;
}
while(q != NULL)
{
st2.push(q);
q = q->next;
}
ListNode *t1 = st1.top();
ListNode *t2 = st2.top();
if(t1 != t2) return NULL;
while(t1 == t2 && !st1.empty() && !st2.empty()) //两个栈都不为空开始退栈
{
t1 = st1.top();
st1.pop();
t2 = st2.top();
st2.pop();
}
if(st1.empty() && !st2.empty()) //一个空一个不为空
{
if(t1 != t2) //如果栈此时已空直接返回next
return t2->next;
else //如果栈不空
{
t2 = st2.top();
st2.pop();
return t2->next;
}
}
else if(!st1.empty() && st2.empty())
{
if(t1 != t2)
{
return t1->next;
}
else
{
t1 = st1.top();
st1.pop();
return t1->next;
}
}
else if(st2.empty() && st1.empty()) //俩都空了
{
if(t1 == t2)
return t1;
return t2->next;
}
else //两个栈都不为空
return t1->next;
}
};