LeetCode:Swap Nodes in Pairs

简介:

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.


给链表添加一个临时的头结点, 这样操作更方便。其实大部分链表问题,添加一个头结点,都会简化后面的操作  本文地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
  * 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) {
         ListNode tmphead(0); tmphead.next = head;
         ListNode *pre = &tmphead, *p = head;
         while (p && p->next) //p 和 p->next是待交换的两个节点,pre是p的前一个节点
         {
             pre->next = p->next;
             p->next = p->next->next;
             pre->next->next = p;
             
             pre = p;
             p = p->next;
         }
         return  tmphead.next;
     }
};





本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3793641.html,如需转载请自行联系原作者

目录
相关文章
|
5月前
Leetcode 24.Swap Nodes in Pairs
 给你一个链表,交换相邻两个节点,例如给你 1->2->3->4,输出2->1->4->3。   我代码里在head之前新增了一个节点newhead,其实是为了少写一些判断head的代码。
22 0
|
索引
LeetCode 336. Palindrome Pairs
给定一组唯一的单词, 找出所有不同 的索引对(i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
92 0
LeetCode 336. Palindrome Pairs
【LeetCode】Palindrome Pairs(336)
  Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a   palindrome.
80 0
LeetCode 25 Reverse Nodes in k-Group(在K组链表中反转结点)(Linked List)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/49815131 原文 给定一个链表,在一定时间内反转这个链表的结点,并返回修改后的链表。
814 0
|
算法
LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/49803287 翻译 给定一个链表,调换每两个相邻节点,并返回其头部。
1127 0
|
22天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
1月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
1月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)