LintCode:交换链表当中两个节点

来源:互联网 发布:unity3d难学吗 编辑:程序博客网 时间:2024/06/05 10:09

一.题目描述

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

 注意事项

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


二.解题思路和代码

想到的方法并不好,等于是先将所有节点取出来,交换之后再重新整成一个链表,如果对时间和空间的要求更为严格的话,这个方法就不行了

 * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */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 hereif (head == null)return null;int i = -1;int j = -1;int index = 0;ArrayList<ListNode> array = new ArrayList<ListNode>();ListNode cursor = head;while (cursor != null) {array.add(cursor);if (cursor.val == v1) {i = index;}if (cursor.val == v2) {j = index;}cursor = cursor.next;index++;}if (i == -1 || j == -1)return head;ListNode temp = array.get(i);array.set(i, array.get(j));array.set(j, temp);int size = array.size();for (int k = 0; k < size - 1; k++) {array.get(k).next = array.get(k + 1);}array.get(size - 1).next = null;return array.get(0);}}