LeetCode 24. Swap Nodes in Pairs
2020-06-03 22:03:25 # leetcode # core problems

Problem

LeetCode 24. Swap Nodes in Pairs

1. 题目简述

给出一个链表,从头开始使其两两交换。例如:

Example:

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

2. 算法思路

也是LeetCode中比较靠前的老题目,其进阶版本LeetCode 25. Reverse Nodes in k-Group

对于这种需要更改链表的题目,包括reverse linked list的题目,最重要的一点就是画图,画图然后去更改每一个指针的指向,然后将当前的节点向后移。否则很容易出错。

这里需要注意的是初次进行swap的时候要进行判断,是否是要和pre的指针相连,如果是初次swap,则pre是null,不需要相连。

指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}

ListNode ret = head.next, ptr = head, pre = null;
while (ptr != null && ptr.next != null) {
ListNode post = ptr.next.next;
ptr.next.next = ptr;
if (pre != null) {
pre.next = ptr.next;
}
ptr.next = post;
pre = ptr;
ptr = ptr.next;
}

return ret;
}
}