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

LeetCode: Swap Nodes in Pairs

2013-04-22 02:56 525 查看
一次过

/**
* 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: