#511 Swap Two Nodes in Linked List

本文介绍了一种在链表中交换两个指定值节点位置的算法实现。通过使用虚拟头节点简化边界条件处理,并讨论了多种特殊情况,如节点不存在、节点相邻等。提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.

 Notice

You should swap the two nodes with values v1 and v2. Do not directly swap the values of the two nodes.

Example

Given 1->2->3->4->null and v1 = 2, v2 = 4.

Return 1->4->3->2->null.

题目思路:

凡是有可能head会加入的题目,我觉得都可以用dummy head这个好东西。比如这题,v1有可能就是1的情况下,用了dummy head,就可以把这种情况当做general case处理啦。这题需要考虑的特殊情况有:

1. v1或者v2找不到

2. v1和v2紧挨着:这里我又分了两种情况 -- v1在v2前面,以及v1在v2后面

3. general swap case

Mycode(AC = 21ms):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param head a ListNode
     * @oaram v1 an integer
     * @param v2 an integer
     * @return a new head of singly-linked list
     */
    ListNode* swapNodes(ListNode* head, int v1, int v2) {
        // Write your code here
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        
        ListNode *ptr1 = dummy, *ptr2 = dummy;
        while (ptr1->next && ptr1->next->val != v1) {
            ptr1 = ptr1->next; // 2
        }
        
        while (ptr2->next && ptr2->next->val != v2) {
            ptr2 = ptr2->next; // 4
        }

        // if can't find one of the values
        if (!ptr1->next || !ptr2->next) {
            return head;
        } 
        // if ptr1 is neighbor of ptr2
        else if (ptr1->next->val == ptr2->val) {
            ptr1->next = ptr2->next;
            ptr2->next = ptr1->next->next;
            ptr1->next->next = ptr2;
        }
        // if ptr2 is before ptr1
        else if (ptr2->next->val == ptr1->val) {
            return swapNodes(head, v2, v1);
        }
        else { // other normal cases
            ListNode *next1 = ptr1->next->next, // 3
                     *next2 = ptr2->next->next, // null
                     *tmp = ptr1->next; // 2
            ptr1->next = ptr2->next; // 
            ptr1->next->next = next1;
            
            ptr2->next = tmp;
            ptr2->next->next = next2;
        }
        
        return dummy->next;
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值