很简单题,值得注意的是因为head会变,所以加一个sentinel节点,sentinel节点都能很优雅地解决head需要改变的问题。另外要注意的是更新curr的时候,由于在swap的时候,curr的为止变了,所以不能用curr = curr.next.next。
代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 sentinel = new ListNode(0); | |
sentinel.next = head; | |
ListNode pre = sentinel; | |
ListNode curr = head; | |
while (curr != null && curr.next != null) { | |
pre.next = swap(curr, curr.next); | |
pre = pre.next.next; | |
curr = pre.next; | |
} | |
return sentinel.next; | |
} | |
private ListNode swap(ListNode l1, ListNode l2) { | |
l1.next = l2.next; | |
l2.next = l1; | |
return l2; | |
} | |
} |
No comments:
Post a Comment