Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Given
1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
比较简单的链表题,主要考察的是链表翻转,但是是翻转的最简单情况。使用一个dummy节点可以比较方便的管理链表头,在处理链表的尾部的时候,由于我使用了双指针操作,所以尤其要注意到达尾部的时候节点为空或者只有一个节点的情况,这些情况可以看做是corner case和在程序一开始就进行判断的情况一样。
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode tail = dummy, temp1 = head, temp2 = head.next;
while(temp1 != null) {
tail.next = temp2;
temp1.next = temp2.next;
temp2.next = temp1;
tail = temp1;
temp1 = temp1.next;
if(temp1 == null || temp1.next == null) break;
temp2 = temp1.next;
}
return dummy.next;
}
没有评论:
发表评论