# 1721. Swapping Nodes in a Linked List ###### tags: `Leetcode` `Medium` `Linked List` Link: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/description/ ## 思路 One pass解法 首先找到从```head```开始的第k个元素 然后我们会发现从找到的这个元素到```head```的距离 刚好就是linkedlist的尾巴到'从尾巴往前数的第k个元素' 因此我们新建一个```temp```等于```head``` 然后让```temp```和```curr```一起动 直到```curr```已经到了linked list的尾巴 这时候只有交换两个node的值即可 ## Code ```python= class Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: curr = head for i in range(k-1): curr = curr.next fromBeginCurr = curr temp = head while curr.next!=None: temp = temp.next curr = curr.next fromEndCurr = temp fromBeginCurr.val, fromEndCurr.val = fromEndCurr.val, fromBeginCurr.val return head ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up