1721. Swapping Nodes in a Linked List You are given theheadof a linked list, and an integerk. Returnthe head of the linked list afterswappingthe values of thekthnode from the beginning and thekthnode from the en
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...
1. Description Swapping Nodes in a Linked List 2. Solution Version 1 classSolution:defswapNodes(self,head:ListNode,k:int)->ListNode:length=0ptr=headwhileptr:length+=1ptr=ptr.nextptr=head count=0whileptr:count+=1ifcount==k:beginning=ptrifcount==length-k+1end=ptr ptr=ptr.nextbeginning.val...
需要特殊判断两个node相邻的情况 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcswapNodes(head*ListNode,k int)*ListNode{varp,q,first,vhead*ListNode vhead=&ListNode{Next:head}p=vheadfork>0{ifk==1{first=p}p=p.Next ...