143. 重排链表 + 链表翻转 + 快慢指针 + 链表合并
143. 重排链表
LeetCode_143
题目描述
代码实现
/**
* 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 void reorderList(ListNode head) {
//首先使用快慢指针找到中间结点
ListNode slow = head, fast = head, pre = null;
while(fast != null){
if(fast.next != null)
fast = fast.next;
pre = slow;
slow = slow.next;
fast = fast.next;
}
//接着翻转后半部分链表
ListNode list2 = reverseLink(slow);//第二个链表是原来链表的后半部分翻转后的结果
ListNode list1 = head;
if(pre != null)
pre.next = null;//第一个链表的尾结点需要为null
//最后合并两个链表
merge(list1, list2);
}
public ListNode reverseLink(ListNode head){//翻转指定结点的链表部分
ListNode pre = null;
while(head != null){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
public void merge(ListNode list1, ListNode list2){//合并两个链表
while(list1 != null && list2 != null){
ListNode temp1 = list1.next;
ListNode temp2 = list2.next;
list1.next = list2;
list2.next = temp1;
list1 = temp1;
list2 = temp2;
}
}
}
Either Excellent or Rusty