*LeetCode-Swap Nodes in Pairs
2015-03-09 07:20
375 查看
指针的判断真的超级容易出错,多想几个test case 1,12,123都想全
几个月前用c++刷的时候
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;
}
}
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;
}
}
相关文章推荐
- [leetcode刷题系列]Swap Nodes in Pairs
- [leetcode]Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs、Reverse Nodes in k-Group、Rotate List
- leetcode -- Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- LeetCode_Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- leetcode 49: Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- leetcode 49: Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- LeetCode Online Judge 题目C# 练习 - Swap Nodes in Pairs
- 【LeetCode with Python】 Swap Nodes in Pairs
- leetcode 14: Swap Nodes in Pairs
- leetcode—Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs