目录
https://leetcode.com/problems/swap-nodes-in-pairs/
将单链表每两个节点互换位置。注意不能只改变节点的值,节点必须实实在在地进行交换。
一、问题描述
测试用例:
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
需要区分节点个数为偶数和奇数的情况,节点个数为奇数时最后一个节点位置不变。
二、代码实现
1、独立处理第一组节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs1(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// the size of list is >= 2
// swap the first 2 nodes
ListNode temp = head;
head = head.next;
temp.next = head.next;
head.next = temp;
ListNode pre = temp;
while (pre.next != null && pre.next.next != null) {
ListNode first = pre.next;
ListNode second = pre.next.next;
pre.next = second;
first.next = second.next;
second.next = first;
//pre -> second -> first
pre = pre.next.next;//pre = first;
}
return head;
}
}
2、引入伪头节点使得处理形式统一起来
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tempHead = new ListNode(-1);
tempHead.next = head;
ListNode pre = tempHead, cur = head;
while (cur != null && cur.next != null) {
ListNode next = cur.next.next;
pre.next = cur.next;
cur.next = next;
pre.next.next = cur;
pre = cur;
cur = next; //cur = cur.next;
}
//cur == null(没有节点了) or cur != null && cur.next == null(只有一个节点)
return tempHead.next;
}
}
3、递归版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs3(ListNode head) {
//1、出口
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
head.next = swapPairs(head.next.next);
newHead.next = head;
return newHead;
}
}
参考:
https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11254/Seeking-for-a-better-solution
https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11019/7-8-lines-C%2B%2B-Python-Ruby