目录
题目:
链接: link
解析:
代码:
java
/**
* 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 newHead = new ListNode(0);
newHead.next = head;
ListNode prev = newHead;
ListNode cur = prev.next, next = cur.next,Nnext = next.next;
while(cur != null && next != null){
//交换节点
prev.next = next;
next.next = cur;
cur.next = Nnext;
//交换之后继续往后走
prev = cur;
cur = Nnext;
if(cur != null)
next = cur.next;
if(next != null)
Nnext = next.next;
}
return newHead.next;
}
}