LeetCode 1721 交换链表中的节点

  • 分析
    链表题,按照题目思路做即可
  • 代码
class Solution {
    
    
public:
    ListNode* swapNodes(ListNode* head, int k) {
    
    
        ListNode* first = head;
        while(--k != 0) first = first -> next;

        ListNode* fast = first;
        ListNode* slow = head;
        while(fast -> next != nullptr){
    
    
            fast = fast -> next;
            slow = slow -> next;
        }

        swap(first -> val, slow -> val);
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/xiaoan08133192/article/details/117131157