问题链接:https://oj.leetcode.com/problems/swap-nodes-in-pairs/
问题描述:Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
问题API:public ListNode reverseKGroup(ListNode head, int k)
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
问题分析:这一题其实就是之前那一题reverse nodes in k-group 里k = 2的状态,所以利用那一题的代码就可以得到答案了,下面给出代码如下:
public void partialReverse(ListNode head, ListNode tail){
ListNode prev = null, next = null, tmp = head, next_group = tail.next;
while(tmp != next_group){
next = tmp.next;
tmp.next = prev;
prev = tmp;
tmp = next;
}
}
public ListNode reverseKGroup(ListNode head, int k) {
int m = k - 1;
ListNode tmp = head, prev = null, new_head = null, next = null, part_head = head, part_tail = null;
while(tmp != null){
m--;
tmp = tmp.next;
if(m == 0 && tmp != null){
next = tmp.next;
part_tail = tmp;
partialReverse(part_head, part_tail);
if(new_head == null)
new_head = part_tail;
if(prev != null)
prev.next = part_tail;
prev = part_head;
part_head.next = next;
part_head = next;
tmp = next;
m = k - 1;
}
}
return new_head == null ? head : new_head;
}
public ListNode swapPairs(ListNode head) {
return reverseKGroup(head, 2);
}
当然,因为reverseKGroup需要照顾到一些泛用性,所以代码会略显冗长。下面给出来的代码会简洁很多,因为只需要处理两个指针即可,所以可以略掉一些步骤:
public ListNode swapPairs(ListNode head) {
if(head == null)
return head;
ListNode prev,next,cur,res;
prev = null;
cur = head;
next = cur.next;
res = head;
while(cur != null && cur.next != null){
next = cur.next;
ListNode nextset = next.next;
if(prev != null){
prev.next = next;
}else{
res = next;
}
next.next = cur;
cur.next = nextset;
prev = cur;
cur = nextset;
}
return res;
}