leetcode 1721. Swapping Nodes in a Linked List | 1721. 交换链表中的节点(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 1721. Swapping Nodes in a Linked List | 1721. 交换链表中的节点(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
題解
思路很簡單:找到左節點,找到右節點,最后交換左右節點的 value 即可。
/*** 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) {int length = 0;ListNode node = head;while (node != null) {length++;node = node.next;}if (length <= 1) return head;ListNode L = head;int left = k - 1;while (left > 0) {L = L.next;left--;}ListNode R = head;int right = length - k;while (right > 0) {R = R.next;right--;}// 題目說swapping the values of the node,所以值交換即可,不需要交換節點int t = L.val;L.val = R.val;R.val = t;return head;} }總結
以上是生活随笔為你收集整理的leetcode 1721. Swapping Nodes in a Linked List | 1721. 交换链表中的节点(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 24. Swap No
- 下一篇: leetcode 19. Remove