leetcode 24 -- Swap Nodes in Pairs

简介:

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 变为 2->1->4->3


思路: 
注意保存pre先前的指针,还要注意特殊情况,有0个或者1个节点。以及链表长度为奇数的情况。


代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */public**//特殊情况,0个或1个节点if==NULL||->==NULLreturn*=*=->//两个节点的情况if->==NULL->=->=NULL=return*=->*=while!=NULL&&!=NULL//改变指针指向=->=->=//向前跳转=->if==NULL==->->=//处理奇数节点的情况if==NULL->=->=->=NULLreturn
相关文章
|
6月前
Leetcode 24.Swap Nodes in Pairs
 给你一个链表,交换相邻两个节点,例如给你 1->2->3->4,输出2->1->4->3。   我代码里在head之前新增了一个节点newhead,其实是为了少写一些判断head的代码。
23 0
|
索引
LeetCode 336. Palindrome Pairs
给定一组唯一的单词, 找出所有不同 的索引对(i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
96 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.
82 0
LeetCode 25 Reverse Nodes in k-Group(在K组链表中反转结点)(Linked List)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/49815131 原文 给定一个链表,在一定时间内反转这个链表的结点,并返回修改后的链表。
817 0
|
算法
LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/49803287 翻译 给定一个链表,调换每两个相邻节点,并返回其头部。
1130 0
|
4天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
4天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
12 0
|
4天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。
25 4
【刷题】 leetcode 面试题 08.05.递归乘法
|
4天前
|
存储 算法 安全
【刷题】 leetcode 面试题 01.06 字符串压缩
来看效果: 非常好!!!过啦!!!
25 5
【刷题】 leetcode 面试题 01.06 字符串压缩