码迷,mamicode.com
首页 > 其他好文 > 详细

24. Swap Nodes in Pairs

时间:2018-03-08 00:01:07      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:its   情况   elf   return   lin   only   change   链表   swap   

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

在不新建一个链表的情况下,交换链表相邻节点。

交换相邻节点A->B,A是head. 

ListNode* p = head;
head = head->next;
p->next = p->next->next;
head->next = p;

整体代码:

 1 class Solution {
 2 public:
 3     ListNode* swapPairs(ListNode* head) {
 4         if (!head || !head->next)
 5             return head;
 6         ListNode* p = head;
 7         head = head->next;
 8         p->next = p->next->next;
 9         head->next = p;
10         ListNode* q = p->next;
11         while (q && q->next) {
12             ListNode *temp = q;
13             q = q->next;
14             temp->next = temp->next->next;
15             q->next = temp;
16             p->next = q;
17             p = q->next;
18             q = p->next;
19         }
20         return head;
21     }
22 };

 

24. Swap Nodes in Pairs

标签:its   情况   elf   return   lin   only   change   链表   swap   

原文地址:https://www.cnblogs.com/Zzz-y/p/8525530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!