Leetcode 24.Swap Nodes in Pairs

简介:  给你一个链表,交换相邻两个节点,例如给你 1->2->3->4,输出2->1->4->3。  我代码里在head之前新增了一个节点newhead,其实是为了少写一些判断head的代码。

 给你一个链表,交换相邻两个节点,例如给你 1->2->3->4,输出2->1->4->3。

  我代码里在head之前新增了一个节点newhead,其实是为了少写一些判断head的代码。

public class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode p = head;
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode newhead = pre;
        while (null != p && null != p.next) {  //两两节点做交换 
        //其实交换两个节点涉及三个节点的变更
            ListNode q = p.next;
            pre.next = p.next;
            p.next = q.next;
            q.next = p;
            pre = p;
            p = p.next;
        }
        return newhead.next;
    }
}
目录
相关文章
|
索引
LeetCode 336. Palindrome Pairs
给定一组唯一的单词, 找出所有不同 的索引对(i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
104 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.
88 0
LeetCode 25 Reverse Nodes in k-Group(在K组链表中反转结点)(Linked List)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/49815131 原文 给定一个链表,在一定时间内反转这个链表的结点,并返回修改后的链表。
824 0
|
算法
LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/49803287 翻译 给定一个链表,调换每两个相邻节点,并返回其头部。
1138 0
|
18天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
18天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
19天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
|
19天前
|
算法
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
|
19天前
|
算法 容器
【LeetCode刷题】滑动窗口解决问题:水果成篮、找到字符串中所有字母异位词
【LeetCode刷题】滑动窗口解决问题:水果成篮、找到字符串中所有字母异位词