24.Swap Nodes in Pairs

题目链接

题目大意:交换单链表中的相邻结点。例子如下:

法一:交换两个相邻的值,不交换相邻结点。代码如下(耗时3ms):

 1     public ListNode swapPairs(ListNode head) {
 2         ListNode cur = head;
 3         while(cur != null && cur.next != null) {
 4             int tmp = cur.val;
 5             cur.val = cur.next.val;
 6             cur.next.val = tmp;
 7             cur = cur.next.next;
 8         }
 9         return head;
10     }
View Code

法二:交换结点,迭代。真的很容易弄晕。代码如下(耗时2ms):

 1     public ListNode swapPairs(ListNode head) {
 2         ListNode res = new ListNode(0);
 3         res.next = head;
 4         ListNode cur = res;
 5         while(cur.next != null && cur.next.next != null) {
 6             //相邻的第一个节点
 7             ListNode pre = cur.next;
 8             //相邻的第二个节点
 9             ListNode post = cur.next.next;
10             //开始交换
11             //将第一个节点的next指向第二个节点的next
12             pre.next = post.next;
13             //加入到结果链表,结果链表的next指向第二个节点,结果链表的next的next指向第一个节点
14             cur.next = post;
15             cur.next.next = pre;
16             //回到遍历
17             cur = cur.next.next;
18         }
19         return res.next;
20     }
View Code
原文地址:https://www.cnblogs.com/cing/p/9334824.html