Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln
reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
链表的题目非常容易出错,要仔细些。尤其要清楚其中的指针是怎么变化的
java
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param head: The head of linked list.
* @return: nothing
*/
public void reorderList(ListNode head) {
// write your code here
if (head == null || head.next == null) {
return;
}
ListNode slow = head;
ListNode fast = head.next;
ListNode mid = null;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
mid = slow;
ListNode tail = reverse(mid.next);
mid.next = null;
merge(head, tail);
}
private ListNode reverse(ListNode head) {
if (head == null) {
return null;
}
ListNode curr = head;
ListNode prev = null;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
private void merge(ListNode head, ListNode tail) {
if (head == null || tail == null) {
return;
}
int index = 0;
ListNode dummy = new ListNode(0);
while (head != null && tail != null) {
dummy.next = head;
head = head.next;
dummy = dummy.next;
dummy.next = tail;
tail = tail.next;
dummy = dummy.next;
}
if (head != null) {
dummy.next = head;
} else {
dummy.next = tail;
}
}
}
python
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: The head of linked list.
@return: nothing
"""
def reorderList(self, head):
# write your code here
if head is None or head.next is None:
return
mid = self.findMid(head)
tail = self.reverse(mid.next)
mid.next = None
self.merge(head, tail)
def findMid(self, head):
slow = head
fast = head.next
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def reverse(self, head):
if head is None:
return head
curr = head
prev = None
while curr is not None:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
def merge(self, head, tail):
if head is None or tail is None:
return
flag = True
dummy = ListNode(-1)
while head is not None and tail is not None:
if flag:
dummy.next = head
head = head.next
else:
dummy.next = tail
tail = tail.next
flag = not flag
dummy = dummy.next
if head is not None:
dummy.next = head
else:
dummy.next = tail