lintcode511. 交换链表当中两个节点

给你一个链表以及两个权值v1和v2,交换链表中权值为v1和v2的这两个节点。保证链表中节点权值各不相同,如果没有找到对应节点,那么什么也不用做。

样例
样例 1:

输入: 1->2->3->4->null, v1 = 2, v2 = 4
输出: 1->4->3->2->null
样例 2:

输入: 1->null, v1 = 2, v2 = 1
输出: 1->null
注意事项
你需要交换两个节点而不是仅仅交换节点的权值

思路:一道普通题,遍历找到两个节点及其前节点,要注意的是两个节点相邻情况的处理即可

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: a ListNode
     * @param 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*firstpre=NULL;
        ListNode*secondpre=NULL;
        ListNode*newhead=new ListNode(0);
        newhead->next=head;
        ListNode*fast=head;
        ListNode*slow=newhead;
        if(head==NULL) return head;
        while(fast)
        {
            if(fast->val==v1) firstpre=slow;
            if(fast->val==v2) secondpre=slow;
            fast=fast->next;
            slow=slow->next;
            if(firstpre&&secondpre) break;
        }
        if(firstpre==NULL||secondpre==NULL) return head;
        ListNode*first=firstpre->next;
        ListNode*second=secondpre->next;
        if(first->next==second)
        {
            first->next=second->next;
            second->next=first;
            firstpre->next=second;
        }
        else if(second->next==first)
        {
            second->next=first->next;
            first->next=second;
            secondpre->next=first;
        }
        else{
            ListNode*tmp=second->next;
            second->next=first->next;
            first->next=tmp;
            firstpre->next=second;
            secondpre->next=first;
        }
        return newhead->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值