No.024: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.

官方难度:

Easy

翻译:

给定一个链表,交换它们每两个的相邻节点,并且返回头结点。

算法必须使用恒定的空间,且不能只交换节点的数据,必须交换节点。

例子:

给定链表:1->2->3->4。

返回链表:2->1->4->3。

  1. 题目规定只能交换节点,如果只需交换数据就简单了。
  2. 首先,定义返回的头结点first,对于长度大于1的链表,返回的头结点是原链表的第二个节点。
  3. 维护当前节点的上一个节点before和下一个节点after。
  4. 进行循环,终止条件是当前节点或下一个节点为null。
  5. 循环内部,首先对after节点赋值,然后依次赋值before,head,after节点的next指针。
  6. 循环结束前,为下一次的循环赋值,替换before和head节点。

解题代码(交换数据):

 1     // 交换结点存放的数据
 2     public static ListNode swapPairsVal(ListNode head) {
 3         ListNode first = head;
 4         while (head != null && head.next != null) {
 5             // 交换数据,一步到位,但有溢出的风险
 6             head.val = head.val + head.next.val - (head.next.val = head.val);
 7             head = head.next.next;
 8         }
 9         return first;
10     }
swapPairsVal

解题代码(交换节点):

 1     // 交换结点
 2     public static ListNode swapPairs(ListNode head) {
 3         // 第一个节点会变
 4         ListNode first = head == null || head.next == null ? head : head.next;
 5         // 上一个节点
 6         ListNode before = new ListNode(0);
 7         ListNode after = new ListNode(0);
 8         while (head != null && head.next != null) {
 9             // 下一个节点
10             after = head.next;
11             // 交换节点
12             before.next = after;
13             head.next = after.next;
14             after.next = head;
15             // 下一次交换赋值
16             before = head;
17             head = head.next;
18         }
19         return first;
20     }
swapPairs

相关链接:

https://leetcode.com/problems/swap-nodes-in-pairs/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q024.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

原文地址:https://www.cnblogs.com/jing-an-feng-shao/p/6178605.html