/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode fakeHead = new ListNode(-1);
fakeHead.next = head;
head = fakeHead;
while(head.next != null && head.next.next != null){
swap(head);
head = head.next.next;
}
return fakeHead.next;
}
public void swap(ListNode node){
ListNode n1 = node.next;
ListNode n2 = node.next.next;
node.next = n2;
n1.next = n2.next;
n2.next = n1;
}
}
Swap Nodes in Pairs
最新推荐文章于 2019-05-11 21:02:45 发布