【Leecode刷题】链表求交点(160)史上最详细系列刷题(含自己环境运行全代码)
原题地址
链表求交点
这里注意两链表不能头相连,头相连不是两个链表了,头结点无法同时指向两个子结点
- 申请数组 L i s t N o d e ListNode ListNode
- 头结点:
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
- 求链表长度:
int list_length(ListNode *head){//待求长度的链表头结点指针
int length=0;
while(head){
length++;
head=head->next;
}
return length;
}
- 指针移动
ListNode *move_pointer(ListNode *head,int count){
//链表头结点指针head与移动的结点数count
for(int i=0; i<count;i++){
//将head指针向前移动count个结点
head=head->next;
}
return head;
};
所有代码汇总,直接能跑的程序
#include<iostream>
using namespace std;
struct ListNode
{
int val;//结点存储的数据
ListNode *next;//指向下一个节点的指针
ListNode(int x):val(x),next(NULL){}//构造函数,将val的值赋为x,next的值赋为空
};
class Solution{
public:
int list_length(ListNode *head){//待求长度的链表头结点指针
int length=0;
while(head){
length++;
head=head->next;
}
return length;
}
ListNode *move_pointer(ListNode *head,int count){
//链表头结点指针head与移动的结点数count
for(int i=0; i<count;i++){
//将head指针向前移动count个结点
head=head->next;
}
return head;
};
ListNode*getlntersectionNode(ListNode*headA,ListNode*headB){
int lengthA=list_length(headA);//计算链表A的长度
int lengthB=list_length(headB);//计算链表B的长度
if(lengthA>lengthB){//比较lengthA与lengthB的大小
//移动较长链表headA,使指针headB与headA对齐
headA=move_pointer(headA,lengthA-lengthB);
}
else{//移动较长链表headB,使指针headB与headA对齐
headB=move_pointer(headB,lengthB-lengthA);
}
ListNode *result=NULL;
while(headA&&headB){
if(headA==headB){
result=headA;
break;
}
headA=headA->next;
headB=headB->next;
}
return result;
}
};
int main()
{
ListNode a(4);
ListNode b(1);
ListNode c(5);
ListNode d(0);
ListNode e(1);
ListNode f(8);
ListNode g(4);
ListNode h(5);
a.next=&b;
b.next=&f;
c.next=&d;
d.next=&e;
e.next=&f;
f.next=&g;
g.next=&h;
Solution solution;
ListNode *result=solution.getlntersectionNode(&a,&c);//提交两个链表的交点地址
printf("%d\n",result->val);
return 0;
/*
std::set<int> check set;//利用STL set找出数组a与b中重复出现的元素
int a[]={4,1,8,4,5};
int b[]={5,0,1,8,4,5};
for(int i=0; i<5;i++){//遍历数组a
check_set.insert(a[])//将a中的元素添加至check_set
}
for(int i=0; i<6;i++){//遍历数组b
//检查b中的元素是否在check_set中出现
if(check_set.find(b[i]!=check_set.end))【
}
*/
}