lintcode 451
作者:互联网
https://www.lintcode.com/problem/451/
[cost]
30 min
[brainstorm]
1 decouple corner case and general case handling.
2 when moving to next two nodes, what case should be considered?
3 how to keep head as return value?
[desc]
1 handle corner cases.
2 handle general case.
keep second node as head to return.
point 1st node from second node.
point 1st node to third fourth nodes block.
go to handle next two nodes.
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: a ListNode
* @return: a ListNode
*/
public ListNode swapPairs(ListNode head) {
// write your code here
if(head==null || head.next==null){
return head;
}
ListNode fir = head;
ListNode sec = fir.next;
ListNode ret = sec;
while(fir!=null && sec!=null){
ListNode third = sec.next;
//swap
sec.next = fir;
fir.next = third;
ListNode last = fir;
//next two nodes
fir = third;
sec = fir==null?null:fir.next;
last.next = sec==null?fir:sec;
}
return ret;
}
}
标签:fir,head,ListNode,451,lintcode,next,sec,null 来源: https://blog.csdn.net/laohixdxm00/article/details/120222036