Description
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p = head; //当前节点k
ListNode q = head.next; //下一节点k+1
ListNode r = null; //记录上一节点k-1
head = q;
while(p != null && q != null) {
p.next = q.next; //交换next
q.next = p;
if(r != null) r.next = q; //更新上一节点的next
r = p; //更新节点
p = p.next;
if(p != null) q = p.next;
}
return head;
}
}

本文介绍了一种在链表中交换每两个相邻节点的算法,该算法仅使用常数额外空间,不修改节点值,仅改变节点本身。通过实例演示了如何将1->2->3->4转换为2->1->4->3。
313

被折叠的 条评论
为什么被折叠?



