作业题
24. 两两交换链表中的节点
public class LeetCode24 { public ListNode swapPairs(ListNode head) { ListNode pre = new ListNode(0); pre.next = head; ListNode temp = pre; while(temp.next != null && temp.next.next != null) { ListNode start = temp.next; ListNode end = temp.next.next; temp.next = end; start.next = end.next; end.next = start; temp = start; } return pre.next; } }
19. 删除链表的倒数第 N 个结点
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode fast = dummy, slow = dummy; int i = 0; for (; i <= n && fast != null; i++) { fast = fast.next; } while (fast != null) { fast = fast.next; slow = slow.next; } if (slow != null && slow.next != null) { slow.next = slow.next.next; } return dummy.next; } }
面试题 02.07. 链表相交
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode first = headA, second = headB; while (first != second) { first = (first !=null) ? first.next : headB; second = (second != null) ? second.next : headA; } return first; } }
142. 环形链表 II
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { // 初始化的时候,均指向头结点 ListNode fast = head, slow = head; while (true) { // 快指针碰到null,说明不存在环 if (fast == null || fast.next == null) { return null; } fast = fast.next.next; slow = slow.next; if (fast == slow) { break; } } // 重新让快指针回到头结点,快慢指针再次相遇时,其距离一定等于a + n * b fast = head; while (fast != slow) { fast = fast.next; slow = slow.next; } return fast; } }
总结
- for 循环的结束条件可以通过临界值带入来判断代码写的是否正确;
- 求倒数第 N 个节点,可以转化为快慢指针,快指针先走 N 步,慢指针再出发,快指针走到尾部,慢指针所在位置即是要求的节点。