LeetCode: Swap Nodes in Pairs

一次过

 1 /**

 2  * Definition for singly-linked list.

 3  * struct ListNode {

 4  *     int val;

 5  *     ListNode *next;

 6  *     ListNode(int x) : val(x), next(NULL) {}

 7  * };

 8  */

 9 class Solution {

10 public:

11     ListNode *swapPairs(ListNode *head) {

12         // Start typing your C/C++ solution below

13         // DO NOT write int main() function

14         ListNode *p, *q, *end, *pPre, *pNext;

15         p = head;

16         q = NULL;

17         while (p) {

18             end = pPre = p;

19             if (p->next) p = p->next;

20             else break;

21             pNext = p->next;

22             p->next = pPre;

23             pPre = p;

24             p = pNext;

25             end->next = p;

26             if (!q) head = pPre;

27             else q->next = pPre;

28             q = end;

29         }

30         return head;

31     }

32 };

 C#

 1 /**

 2  * Definition for singly-linked list.

 3  * public class ListNode {

 4  *     public int val;

 5  *     public ListNode next;

 6  *     public ListNode(int x) { val = x; }

 7  * }

 8  */

 9 public class Solution {

10     public ListNode SwapPairs(ListNode head) {

11         ListNode p = head, q = null, end = head, pPre = head, pNext = null;

12         while (p != null) {

13             end = pPre = p;

14             if (p.next != null) p = p.next;

15             else break;

16             pNext = p.next;

17             p.next = pPre;

18             pPre = p;

19             p = pNext;

20             end.next = p;

21             if (q == null) head= pPre;

22             else q.next = pPre;

23             q = end;

24         }

25         return head;

26     }

27 }
View Code

 

你可能感兴趣的:(LeetCode)