相交链表
思路
- 链表交叉不可能是x型
- 因为有可能两个链表不等长,所以我们必须让他们从同一起跑位置去起跑
- 从同一起跑位置出发,依次比较每个结点的地址是否相同
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*///求长度
int getLength(struct ListNode *head){int n = 0;struct ListNode *cur =head;while(cur != NULL){cur = cur->next;n++;}return n;
}struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {int lenA =getLength(headA);int lenB =getLength(headB);struct ListNode *longHead;struct ListNode *shortHead;int diff; //两个链表的长度之差if(lenA >= lenB){longHead = headA;shortHead = headB;diff =lenA - lenB;}else{longHead = headB;shortHead = headA;diff =lenB - lenA; }for(int i = 0; i < diff; i++){ //把两个链表放在同一起跑位置longHead =longHead->next;}while (longHead != shortHead){ //对结点的地址进行比较longHead =longHead->next;shortHead = shortHead->next;}return longHead;
}
环形链表
思路
- 两个指针,一个跑两格,一个跑一格,如果快的能把满的追上就说明有环
- 快指针每跑一格,都要进行判空,如果为空,就说明没有环
- 还要注意初始的head就为空的情况
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
bool hasCycle(struct ListNode *head) {if(head == NULL){return false;}struct ListNode *fast = head;struct ListNode *slow = head;while(1){fast = fast->next;if(fast == NULL){return false;}fast = fast->next;if(fast == NULL){return false;}slow = slow->next;if(fast == slow){return true;}}
}
返回链表开始入环的第一个节点
思路
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode *detectCycle(struct ListNode *head) {if(head == NULL){return NULL;}struct ListNode *fast =head;struct ListNode *slow =head;while(1){//先找相遇点fast = fast->next;if(fast == NULL){return NULL;}fast =fast->next;if(fast == NULL){return NULL;}slow =slow->next;if(fast == slow){break;}}//一个从相遇点开始,另外一个从起始点开始,他们的相遇点就是开始入环的第一个结点struct ListNode *n1 =head;struct ListNode *n2 =slow;while( n1 != n2){n1=n1->next;n2=n2->next;} return n1;
}