Reverse second half of linked list
Suppose we have 1-2-3-4
Output: 1-2-4-3
Suppose we have 1-2-3-4-5
Output: 1-2-3-5-4 // however I want the output to be 1-2-5-4-3 in the odd condition, how to modify the code below?
public static ListNode reverseSecondHalfList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode pre = slow.next;
ListNode cur = pre.next;
while (cur != null) {
pre.next = cur.next;
cur.next = slow.next;
slow.next = cur;
cur = pre.next;
}
return head;
}
My method: Firstly find the start position to be swapped, then swap "pre" node and "cur" each time until cur.next!=null
Try this
public static ListNode reverseSecondHalfList(ListNode head) {
if (head == null || head.next == null) return head;
// Add one more node before head, it will help us find the node which before mid note.
ListNode newHead = new ListNode(0);
newHead.next= head;
ListNode fast = newHead;
ListNode slow = newHead;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode pre = slow.next;
ListNode cur = pre.next;
while (cur != null) {
pre.next = cur.next;
cur.next = slow.next;
slow.next = cur;
cur = pre.next;
}
return head;
}
And I extract some code from one method make code cleaner
public static ListNode reverseSecondHalfList2(ListNode head) {
if (head == null || head.next == null) return head;
ListNode preMid = getPreMidListNode(head);
reverse(preMid);
return head;
}
private static void reverse(ListNode preMid) {
ListNode pre = preMid.next;
ListNode cur = pre.next;
while (cur != null) {
pre.next = cur.next;
cur.next = preMid.next;
preMid.next = cur;
cur = pre.next;
}
}
private static ListNode getPreMidListNode(ListNode head) {
// Add one more node before head, it will help us find the node which before mid note.
ListNode newHead = new ListNode(0);
newHead.next= head;
ListNode fast = newHead;
ListNode slow = newHead;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.