Swap Two Nodes in Linked List

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.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @oaram v1 an integer
     * @param v2 an integer
     * @return a new head of singly-linked list
     */
    public ListNode swapNodes(ListNode head, int v1, int v2) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        ListNode first = null, second = null;
        while(head.next != null) {
            if(head.next.val == v1) {
                first = head;
            } else if(head.next.val == v2) {
                second = head;
            }
            head = head.next;
        }
        if(first == null || second == null) {
            return dummy.next;
        }
        if(second.next == first) {//make sure that the first is always before the second
            ListNode temp = second;
            second = first;
            first = temp;
        }
        if(first.next == second) {//if these two nodes are adjacent
            ListNode third = second.next;
            first.next = third;
            ListNode temp = third.next;
            third.next = second;
            second.next = temp;
        } else {
            ListNode node1 = first.next;
            ListNode post1 = node1.next;
            ListNode node2 = second.next;
            ListNode post2 = node2.next;
            first.next = node2;
            node2.next = post1;
            second.next = node1;
            node1.next = post2;
        }
        return dummy.next;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值