回文链表
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
if (head.next == null) {
return true;
}
ListNode mid = getMid(head);
ListNode n1 = revert(mid.next);
while (n1 != null) {
if (head.val != n1.val) {
return false;
}
head = head.next;
n1 = n1.next;
}
return true;
}
public ListNode revert(ListNode head) {
if (head.next == null) {
return head;
}
ListNode next = revert(head.next);
head.next.next = head;
head.next = null;
return next;
}
public ListNode getMid(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null) {
fast = fast.next;
if (fast != null && fast.next != null ) {
fast = fast.next;
slow = slow.next;
}
}
return slow;
}
}
重排链表
class Solution {
public void reorderList(ListNode head) {
if (head == null) {
return;
}
ListNode mid = getMid(head);
ListNode temp = mid.next;
mid.next = null;
ListNode node1 = revertStack(temp);
ListNode c = head;
while (node1 != null) {
temp = node1.next;
node1.next = c.next;
c.next = node1;
c = node1.next;
node1 = temp;
}
}
public ListNode getMid(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public ListNode revertStack(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = revertStack(head.next);
head.next.next = head;
head.next = null;
return next;
}
public ListNode revertLocal(ListNode head) {
ListNode emptyHead = new ListNode(-1, head);
ListNode current = emptyHead.next;
ListNode next = emptyHead.next.next;
while (next != null) {
ListNode temp = next.next;
next.next = current;
current = next;
next = temp;
}
return head;
}
}