Swap Two Nodes in Linked List

来源:互联网 发布:tomcat启动端口号 编辑:程序博客网 时间:2024/06/06 05:53

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
原创粉丝点击