lintcode--511. 交换链表当中两个节点

描述

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

你需要交换两个节点而不是改变节点的权值

样例

给出链表 1->2->3->4->null ,以及 v1 = 2 , v2 = 4
返回结果 1->4->3->2->null

代码

根据给定的两个值,交换两个节点,有两种情况(在两个节点能找到的情况下),一种是两个相邻,另一种是不相邻。

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: a ListNode
     * @param v1: An integer
     * @param v2: An integer
     * @return: a new head of singly-linked list
     */
    public ListNode swapNodes(ListNode head, int v1, int v2) {
        // write your code here
        if(head==null){
            return null;
        }
        ListNode node=new ListNode(1);
        node.next=head;
        ListNode cur=head,pre1=null,pre2=null,pre=node;
        while(cur!=null){
            if(cur.val==v1||cur.val==v2){
                if(pre1==null){
                    pre1=pre;
                }else if(pre2==null){
                    pre2=pre;
                    break;
                }
            }
            pre=cur;
            cur=cur.next;
        }
        if(pre1==null||pre2==null){
            node.next=null;//help gc
            return head;
        }
        if(pre1.next==pre2){ //相邻的情况
            ListNode node2=pre2.next;
            pre1.next=node2;
            pre2.next=node2.next;
            node2.next=pre2;
        }else{             //不相邻的情况
            ListNode node1=pre1.next,node2=pre2.next;
            ListNode next1=node1.next;
            ListNode next2=node2.next;
            pre1.next=node2;
            node2.next=next1;
            node1.next=next2;
            pre2.next=node1;
        }
        return node.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值