# 1721.Swapping Nodes in a Linked List ###### tags: `leetcode`,`list`,`medium` **list** >ref: 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 beginning and the kth node from the end (the list is 1-indexed). >Example 1: ![](https://i.imgur.com/VSOcVQU.png) 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] >Constraints: The number of nodes in the list is n. 1 <= k <= n <= 10^5 0 <= Node.val <= 100 >1. loop 2次list 第一次找k跟k-1 node(1 base), 第二次找len-k跟len-k+1(1 base) node, 兩pre node\(k-1/len-k)最多只會有一個為null,此時置換node(k/len-k+1)為首尾交換 >2. timeCom需loop完整一次與紀錄四node,最差為log(2N), spatialCom為固定四node,log(1) constant ```java= /** * 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 swapNodes(ListNode head, int k) { ListNode t1=null;//pre ListNode t2=null; ListNode t4=null;//pre ListNode t5=null; ListNode cur= head; int count=0; //k-1 and k node while(cur !=null){ count++; if(count==k-1){ t1=cur; } if(count==k){ t2=cur; } cur=cur.next; } k=count-k+1; count=0; cur=head; //len-k and len-k+1 node while(cur !=null){ count++; if(count==k-1){ t4=cur; } if(count==k){ t5=cur; } cur=cur.next; } //是否首尾交換 if(t1==null){ head=t5; }else{ t1.next=t5; } //是否首尾交換 if(t4==null){ head=t2; }else{ t4.next=t2; } // 兩交換node的next交換 ListNode temp; temp=t2.next; t2.next=t5.next; t5.next=temp; return head; } } ```