zoukankan      html  css  js  c++  java
  • 1721. Swapping Nodes in a Linked List (M)

    Swapping Nodes in a Linked List (M)

    题目

    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 <= 10^5
    • 0 <= Node.val <= 100

    题意

    交换链表中第k个结点和倒数第k个结点的值。

    思路

    指针p指向head向后移动,当p指向第k个结点时,指针q指向head并随p一起向后移动,当p指向最后一个结点时,q指向倒数第k个结点。


    代码实现

    Java

    class Solution {
        public ListNode swapNodes(ListNode head, int k) {
            ListNode p = head, q = null;
            ListNode a = null, b = null;
            
            while (k > 1) {
                p = p.next;
                k--;
            }
            a = p;
            q = head;
            
            while (p.next != null) {
                p = p.next;
                q = q.next;
            }
            b = q;
            
            int tmp = a.val;
            a.val = b.val;
            b.val = tmp;
            
            return head;
        }
    }
    
  • 相关阅读:
    Ubuntu14.04LTS系统QQ的安装:pidgin-lwqq
    Ubuntu14.04LTS系统输入法的安装
    Linux系统安装及初始化(ubuntu14.04)
    创建RAID并永久挂载RAID
    磁盘管理和磁盘配额
    用户账号组账号概述
    安装及管理程序
    目录和文件管理
    Vi编辑器的工作模式
    Linux命令及使用方法
  • 原文地址:https://www.cnblogs.com/mapoos/p/14533055.html
Copyright © 2011-2022 走看看