zoukankan      html  css  js  c++  java
  • [LeetCode] 1721. Swapping Nodes in a Linked List

    You are given the head of a linked list, and an integer k.

    Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). 

    Example 1:

    Input: head = [1,2,3,4,5], k = 2
    Output: [1,4,3,2,5]
    

    Example 2:

    Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
    Output: [7,9,6,6,8,7,3,0,9,5]
    

    Example 3:

    Input: head = [1], k = 1
    Output: [1]
    

    Example 4:

    Input: head = [1,2], k = 1
    Output: [2,1]
    

    Example 5:

    Input: head = [1,2,3], k = 2
    Output: [1,2,3]

    Constraints:

    • The number of nodes in the list is n.
    • 1 <= k <= n <= 105
    • 0 <= Node.val <= 100

    交换链表中的节点。

    给你链表的头节点 head 和一个整数 k 。交换链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。

    由于只需要swap两个节点的node.val,所以这道题简单很多。这里我提供一个双指针的思路。首先我们计算一下链表的长度len,得到这个长度之后,因为要交换的节点是正数第 K 个和倒数第 K 个节点,其中倒数第 K 个节点正数的index = len + 1 - k。依据这个信息,我们用两个指针从head节点开始遍历,分别在两个被swap的节点停下,swap他们的节点值即可。

    时间O(n)

    空间O(1)

    Java实现

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode() {}
     7  *     ListNode(int val) { this.val = val; }
     8  *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     9  * }
    10  */
    11 class Solution {
    12     public ListNode swapNodes(ListNode head, int k) {
    13         int len = 0;
    14         ListNode cur = head;
    15         while (cur != null) {
    16             cur = cur.next;
    17             len++;
    18         }
    19 
    20         int first = k;
    21         int second = len + 1 - k;
    22         int i = 1;
    23         ListNode p = head;
    24         while (p != null && i != first) {
    25             p = p.next;
    26             i++;
    27         }
    28 
    29         int j = 1;
    30         ListNode q = head;
    31         while (q != null && j != second) {
    32             q = q.next;
    33             j++;
    34         }
    35 
    36         int temp = p.val;
    37         p.val = q.val;
    38         q.val = temp;
    39         return head;
    40     }
    41 }

    LeetCode 题目总结

  • 相关阅读:
    [BFS]luogu P2536 [AHOI2005]病毒检测
    AtCoder Regular Contest 116 总结
    NOI online 2021 #1 总结
    博客半复活
    vue2 Bus兄弟组件间传值问题:重复触发和首次未触发
    ant design中table组件的filter,如何在外部控制
    ant design vue 日期排序
    什么是断点续传?前端如何实现文件的断点续传
    主vue前端面试题补充
    P4248 [AHOI2013]差异 题解
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14547079.html
Copyright © 2011-2022 走看看