lintcode-medium-Swap Two Nodes in Linked List

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-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) {
        // Write your code here
        
        if(head == null || head.next == null)
            return head;
        
        if(v1 == v2)
            return head;
        
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        
        ListNode p1 = fakehead;
        ListNode p2 = fakehead;
        
        while(p1.next != null){
            if(p1.next.val == v1)
                break;
            
            p1 = p1.next;
        }
        
        if(p1.next == null)
            return head;
        
        while(p2.next != null){
            if(p2.next.val == v2)
                break;
            
            p2 = p2.next;
        }
        
        if(p2.next == null)
            return head;
        
        ListNode node1 = p1.next;
        p1.next = null;
        ListNode node2 = p2.next;
        p2.next = null;
        
        p2.next = node1;
        p1.next = node2;
        
        ListNode head2 = null;
        ListNode head3 = null;
        
        if(node1.next != null)
            head2 = node1.next;
        else
            head2 = null;
        
        if(node2.next != null)
            head3 = node2.next;
        else
            head3 = null;
        
        node2.next = head2;
        node1.next = head3;
        
        return fakehead.next;
    }
}

 

以上是关于lintcode-medium-Swap Two Nodes in Linked List的主要内容,如果未能解决你的问题,请参考以下文章

Mark Compact GC (Part two :Two-Finger)

two.js文档阅读笔记-two.js的基本使用

Two Scoops Press Two Scoops of Django 1.11.pdf

[LeetCode] 349 Intersection of Two Arrays & 350 Intersection of Two Arrays II

1. Two Sum

URAL 1495 One-two, One-two 2