Reorder List
题目地址:
https://leetcode.com/problems/reorder-list/description/
题目:
这道题主要综合了三个知识点:链表找中点,反转链表和merge链表。
代码:
https://leetcode.com/problems/reorder-list/description/
题目:
Given a singly linked list L: L0?L1?…?Ln-1?Ln,
reorder it to: L0?Ln?L1?Ln-1?L2?Ln-2?…
reorder it to: L0?Ln?L1?Ln-1?L2?Ln-2?…
You must do this in-place without altering the nodes' values.
For example,
Given
解题思路:Given
{1,2,3,4}, reorder it to {1,4,2,3}.这道题主要综合了三个知识点:链表找中点,反转链表和merge链表。
代码:
public class ReorderList { public static void main(String[] args){ ReorderList reorderList = new ReorderList(); ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); ListNode n4 = new ListNode(4); ListNode n5 = new ListNode(5); ListNode n6 = new ListNode(6); ListNode n7 = new ListNode(7); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; n6.next = n7; reorderList.reorderList(n1); while(n1 != null){ System.out.print(n1.val + "-"); n1 = n1.next; } } public void reorderList(ListNode head) { if(head == null || head.next == null || head.next.next == null){ return; } ListNode fast = head; ListNode slow = head; // this slow pointer will stay at the mid point for list with odd number // the slow pointer will stay at the node closer to the head among the mid two node while(fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; } ListNode head1 = head; ListNode oldHead2 = slow.next; slow.next = null; ListNode head2 = reverse(oldHead2); merge(head1, head2); } private void merge(ListNode head1, ListNode head2) { ListNode dummy = new ListNode(-1); ListNode curr = dummy; int count = 0; while(head1 != null && head2 != null){ if(count % 2 == 0){ curr.next = head1; head1 = head1.next; } else{ curr.next = head2; head2 = head2.next; } count++; curr = curr.next; } if(head1 != null){ curr.next = head1; } if(head2 != null){ curr.next = head2; } head1 = dummy.next; } // iterative way public ListNode reverse(ListNode head) { if(head == null || head.next == null){ return head; } ListNode curr = head; ListNode next = curr.next; curr.next = null; while(next != null){ ListNode nextnext = next.next; next.next = curr; curr = next; next = nextnext; } return curr; } // recursion might overflow// public ListNode reverse(ListNode head) {// if(head == null || head.next == null){// return head;// }// ListNode next = head.next;// ListNode newHead = reverse(next);// next.next = head;// head.next = null;// return newHead;// } }

Comments
Post a Comment