LeetCode 24. Swap Nodes in Pairs题目分析代码

题目

给一个链表,两两交换其中的节点,然后返回交换后的链表。

样例 给出 1->2->3->4, 你应该返回的链表是 2->1->4->3。

分析

由于没有头结点不好操作 那就自己加一个头结点

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @return a ListNode
     */
    public ListNode swapPairs(ListNode head) {
        // Write your code here
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        head = dummy;
        while (head.next != null && head.next.next != null) {
            ListNode n1 = head.next, n2 = head.next.next;
            // head->n1->n2->...
            // => head->n2->n1->...
            head.next = n2;
            n1.next = n2.next;
            n2.next = n1;
            
            // move to next pair
            head = n1;
        }
        
        return dummy.next;
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏深度学习与计算机视觉

数据结构-单链表的读取,插入与删除

链表定义: struct ListNode { int value; ListNode *next; }; 单链表读取 在顺序存储结构中,比如数组中,想...

23970
来自专栏计算机视觉与深度学习基础

Leetcode 2 Add Two Numbers

题目没有说清楚,trick挺多,考察细心程度的水题吧。 You are given two linked lists representing two ...

21960
来自专栏WD学习记录

LeetCode Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers....

9710
来自专栏Jack-Cui

83. Remove Duplicates from Sorted List(Linked List-Easy)

Given a sorted linked list, delete all duplicates such that each element appear ...

20670
来自专栏desperate633

LintCode 链表划分题目代码

样例 给定链表 1->4->3->2->5->2->null,并且 x=3 返回** 1->2->2->4->3->5->null**

7820
来自专栏aCloudDeveloper

LeetCode: 2_Add Two Numbers | 两个链表中的元素相加 | Medium

题目: You are given two linked lists representing two non-negative numbers. The di...

21360
来自专栏计算机视觉与深度学习基础

Leetcode 82 Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leavi...

20650
来自专栏Jack-Cui

21. Merge Two Sorted Lists(Linked List-Easy)

Merge two sorted linked lists and return it as a new list. The new list should b...

202100
来自专栏LeetCode

LeetCode 206. Reverse Linked List

11120
来自专栏Jack-Cui

206. Reverse Linked List(Linked List-Easy)

Reverse a singly linked list. Hint: A linked list can be reversed either iterati...

22060

扫码关注云+社区

领取腾讯云代金券