
刷题篇
一、回文链表
1.1 题目描述


1.2 思路分析
1.3 代码演示
public boolean isPalindrome(ListNode head) {
if (head == null) {
return false;
}
ListNode firstHalfEnd = endOfFirstList(head);
ListNode firstHaftStart = reverse(firstHalfEnd.next);
boolean result = true;
ListNode p1 = head;
ListNode p2 = firstHalfStart;
while(result && p2 != null) {
if(p1.val != p2.val) {
result = false;
}
p1 = p1.next;
p2 = p2.next;
}
firstHaftEnd.next = reverse(firstHalfEnd.next);
return result;
}
public static ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
public static ListNode endOfFirstList(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
二、环形链表
2.1 题目描述



2.2 思路分析
2.3 代码演示
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode fast = head.next;
ListNode slow = head;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}
三、合并两个有序链表
3.1 题目描述


3.2 思路分析
3.3 代码演示
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null && list2 == null) {
return null;
}
if(list1 == null && list2 != null) {
return list2;
}
if(list1 != null && list2 == null) {
return list1;
}
ListNode preHead = new ListNode(-1);
ListNode prev = preHead;
while(list1 != null && list2 != null) {
if(list1.val < list2.val) {
prev.next = list1;
list1 = list1.next;
} else {
prev.next = list2;
list2 = list2.next;
}
prev = prev.next;
}
prev.next = list1 == null ? list2 : list1;
return preHead.next;
}