道阻且长,行则将至,走慢一点没关系,不停下就|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-11 21:01阅读: 2评论: 0推荐: 0

[LeetCode Hot 100] LeetCode24. 两两交换链表中的节点

题目描述

思路:

  • 创建dummy节点,令dummy.next = head。令cur表示当前到达的节点,初始时cur = dummy。每次需要交换cur后面的两个节点。
  • 如果cur的后面没有节点或者只有一个节点,则没有更多的节点需要交换,因此结束交换。否则,获得cur后面的两个节点node1和node2,通过更新节点的指针关系实现两两交换节点。
cur.next = node2;  // 步骤1
node1.next = node2.next; // 步骤2
node2.next = node1; // 步骤3

方法一:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode cur = dummy;
        while (cur.next != null && cur.next.next != null) {
            ListNode node1 = cur.next;
            ListNode node2 = cur.next.next;
            cur.next = node2;
            node1.next = node2.next;
            node2.next = node1;
            cur = node1;
        }
        return dummy.next;
    }
}

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17895540.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(2)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.