您的位置:首页 > Web前端 > Node.js

*LeetCode-Swap Nodes in Pairs

2015-03-09 07:20 375 查看
指针的判断真的超级容易出错,多想几个test case 1,12,123都想全

public class Solution {
public ListNode swapPairs(ListNode head) {
if ( head == null || head.next == null )
return head;
ListNode dummy = new ListNode(0);
ListNode pre = dummy;
ListNode first = head;
ListNode second = head.next;
while ( second!= null ){ //这个判断条件错了好几次
pre.next = second;
first.next = second.next;
second.next = first;
pre = first;
first = first.next;
if ( first == null ) //这里要多判断一下
break;
second = first.next;
}
return dummy.next;
}
}


几个月前用c++刷的时候

ListNode *swapPairs(ListNode *head) {
if ( head == NULL || head->next == NULL)
return head;
else {
ListNode * tempP = head;
ListNode * tempPNext;
ListNode *ret=head->next;
ListNode *last=new ListNode(0);
while (tempP!= NULL && tempP->next!=NULL ){
tempPNext = tempP->next;
last->next=tempPNext;
tempP->next = tempP->next->next;
tempPNext->next = tempP;
last=tempP;
tempP = tempP->next;
}
return ret;
}
}

discuss里面的recursive 但是超级难想 而且空间是n

public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: