• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 

posted @ 2013-04-22 02:56  ying_vincent  阅读(136)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3