程序媛詹妮弗
终身学习

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

 

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

 

题意:

给定一个链表,每两个节点做一下交换。

 

Solution1: Two Pointers(fast & slow) 

(1) use Two Pointers(fast & slow)  to find a pair

(2)swap

(3) move forward to find a new pair

 

 

code:

 1 /*
 2 Time: O(n)
 3 Space: O(1) 
 4 */
 5 class Solution {
 6        public ListNode swapPairs(ListNode head) {
 7         ListNode dummy = new ListNode(-1);
 8         dummy.next = head;
 9         head = dummy;
10         while (head.next != null && head.next.next != null) {
11             // narrow to find a pair
12             ListNode slow = head.next;
13             ListNode fast = head.next.next;
14             
15             // swap
16             head.next = fast;
17             slow.next = fast.next;
18             fast.next = slow;
19             
20             // move to next pair
21             head = slow;
22         }
23         return dummy.next;
24     }
25 }

 

posted on 2019-04-09 03:32  程序媛詹妮弗  阅读(135)  评论(0编辑  收藏  举报