Loop solution: notice the loop condition is node != null && node.next != null, and set the preNode.next to new swapped node too!
/**
* 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) {
if(head == null || head.next == null){
return head;
}
ListNode newHead = new ListNode(Integer.MIN_VALUE);
newHead.next = head;
ListNode preNode = newHead;
ListNode node = preNode.next;
while(node != null && node.next != null){
ListNode temp = node.next;
preNode.next = temp;
node.next = temp.next;
temp.next = node;
preNode = node;
node = node.next;
}
return newHead.next;
}
}
没有评论:
发表评论