ListNode next) { this.val = val; this.next = next; }9* }10*/11classSolution {12publicListNode swapNodes(ListNode head,intk) {13intlen = 0;14ListNode cur =head;15while(cur !=null)
package LeetCode_1721 /** * 1721. Swapping Nodes in a Linked List * https://leetcode.com/problems/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...
[LeetCode] 1721. Swapping Nodes in a Linked List You are given theheadof a linked list, and an integerk. Returnthe head of the linked list after swapping the values of thekthnode from the beginning and thekthnode from the end (the list is 1-indexed). Example 1: Input: head = [1...
one-pass solution就是用两个指针,找到两个node直接交换val即可 如果题目要求必须实现node的交换,则需要找到两个node的前一个node,进行swap 需要特殊判断两个node相邻的情况 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcswapNodes(head*ListNode...