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

LeetCode 24. Swap Nodes in Pairs

时间:2018-01-01 23:39:49      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:etc   style   odi   ini   link   efi   sel   题目   tno   

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.

 

题目要求成对翻转指针,难度一般,要求使用常数的空间,应当使用迭代的方法而非递归的方法,这里我们加上一个头结点dummy,这样一来即使翻转的节点涉及到头结点,需要修改头指针,我们也可以做到和一般节点一样处理,我们设置了一个指针pre指向“一对”节点,一个指针t指向一对节点的第二个节点

【图解稍后补充】

代码如下:

 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         ListNode *dummy = new ListNode(-1), *pre = dummy;
13         dummy->next = head;
14         while (pre->next && pre->next->next)
15         {
16             ListNode *t = pre->next->next;
17             pre->next->next = t->next;
18             t->next = pre->next;
19             pre->next = t;
20             pre = t->next;
21         }
22         return dummy->next;
23     }
24 };

 

LeetCode 24. Swap Nodes in Pairs

标签:etc   style   odi   ini   link   efi   sel   题目   tno   

原文地址:https://www.cnblogs.com/dapeng-bupt/p/8169113.html

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