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 c1 → c2 → c3 B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
题意:找出两个两个链表的相交点
解法:先算出两个链表的长度,同时遍历两个链表,较短的链表从位于Math.Abs(countA - countB)的节点开始遍历,直到两个指针指向的节点相同
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode GetIntersectionNode(ListNode headA, ListNode headB) {
int countA = GetCount(headA);
int countB = GetCount(headB);
int offset = Math.Abs(countA - countB);
if (countA > countB) {
headA = GetIndex(headA, offset);
} else {
headB = GetIndex(headB, offset);
}
while (headA != null && headB!=null) {
if (headA.GetHashCode() == headB.GetHashCode()) {
return headA;
} else {
headA = headA.next;
headB = headB.next;
}
}
return null;
}
public ListNode GetIndex(ListNode head,int index) {
int count = 0;
ListNode node = head;
while (node != null) {
if (count == index) {
return node;
} else {
count++;
node = node.next;
}
}
return null;
}
public int GetCount(ListNode head) {
int count = 0;
ListNode node = head;
while (node != null) {
count++;
node = node.next;
}
return count;
}
}
时间: 2024-11-05 12:10:42