LeetCode: Swap Nodes in Pairs
2013-04-22 02:56
525 查看
一次过
C#
View Code
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function ListNode *p, *q, *end, *pPre, *pNext; p = head; q = NULL; while (p) { end = pPre = p; if (p->next) p = p->next; else break; pNext = p->next; p->next = pPre; pPre = p; p = pNext; end->next = p; if (!q) head = pPre; else q->next = pPre; q = end; } return head; } };
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode SwapPairs(ListNode head) { ListNode p = head, q = null, end = head, pPre = head, pNext = null; while (p != null) { end = pPre = p; if (p.next != null) p = p.next; else break; pNext = p.next; p.next = pPre; pPre = p; p = pNext; end.next = p; if (q == null) head= pPre; else q.next = pPre; q = end; } return head; } }
View Code
相关文章推荐
- LeetCode:Swap Nodes in Pairs
- LeetCode - M - Swap Nodes in Pairs
- LeetCode--Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- [Leetcode]Swap Nodes in Pairs
- Leetcode 24.Swap Nodes in Pairs
- Java [leetcode 24]Swap Nodes in Pairs
- leetcode(11)24. Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- LeetCode-24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs ***** 双节点交换
- 【Leetcode】Swap Nodes in Pairs
- Leetcode——24. Swap Nodes in Pairs
- 【leetcode每日一题】24.Swap Nodes in Pairs
- leetcode Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs