160. Intersection of Two Linked Lists (Easy)
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
複製程式碼
- 思路:
- 連結串列A的長度為a+c,連結串列B的長度為b+c,c為公共部分長度,所以有a+c+b=b+c+a,即指標先走完A連結串列然後繼續從B連結串列頭開始走,B指標走完B連結串列然後從A連結串列頭開始走,如果兩個連結串列相交,那麼A、B兩個指標就會在共同連結串列相遇
- 程式碼:
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int count = 0;
ListNode l1 = headA, l2 = headB;
while (l1 != l2) {
if (l1 == null) {
count++;
if (count == 2) {
return null;
}
l1 = headB;
} else {
l1 = l1.next;
}
l2 = l2 == null ? headA : l2.next;
}
return l1;
}
複製程式碼
206. Reverse Linked List (Easy)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode temp;
ListNode newHead = null;
while (head.next != null) {
temp = head.next;
head.next = newHead;
newHead = head;
head = temp;
}
head.next = newHead;
return head;
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode temp;
ListNode newHead = new ListNode(0);
while (head != null) {
temp = head.next;
head.next = newHead.next;
newHead.next = head;
head = temp;
}
return newHead.next;
}
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
ListNode newHead = reverseList(next);
head.next = null;
next.next = head;
return newHead;
}
複製程式碼
21. Merge Two Sorted Lists (Easy)
class Solution {
public ListNode head;
public ListNode tail;
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
head = tail = null;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
add(l1);
l1 = l1.next;
} else {
add(l2);
l2 = l2.next;
}
}
if (l1 != null) {
add(l1);
} else if (l2 != null) {
add(l2);
}
return head;
}
public void add(ListNode next) {
if (head == null) {
head = tail = next;
} else {
tail.next = next;
tail = next;
}
}
}
複製程式碼