简体   繁体   English

交换单链表中的节点 java

[英]Swapping nodes in a singly linked list java

I have been trying to come up with an algorithm to swap 2 nodes (not necesarily right next to each other) in a singly linked list for 2 days but for some reason I cannot do it.我一直在尝试想出一种算法来交换单向链表中的 2 个节点(不一定彼此相邻)2 天,但由于某种原因我不能这样做。 Here is what I have, I am really new to coding and have been really stressed:这就是我所拥有的,我对编码真的很陌生并且压力很大: 在此处输入图像描述 I have managed to place a temp node in but can't actually swap the nodes.我设法放置了一个临时节点,但实际上无法交换节点。

public void swap(int i, int j) {
    current = head;
    current2 = head;
    sllNode temp = new sllNode(" ");
    sllNode temp2 = new sllNode(" ");

    for(int z = 0; i>z; z++)
        current=current.next;
    for(int q = 0; j>q; q++)
        current2 = current2.next;

    temp.next = current2.next.next;
    current.next = temp;
    current.next = current2.next.next;
    current2.next = current;

Why exchange nodes, when you can exchange the data? 为什么可以交换节点,何时可以交换数据?

public void swap(int i, int j) {

    sllNode ithNode = head;
    for (int z = 0; z < i; z++) {
        ithNode = ithNode.next;
    }

    sllNode jthNode = head;
    for (int q = 0; q < j; q++) {
        jthNode = jthNode.next;
    }

    // Swap the data        
    String data = ithNode.data;
    ithNode.data = jthNode.data;
    jthNode.data = data;
}

It would make sense to use a method: 使用一种方法很有意义:

public sllNode get(int i) {
    sllNode current = head;
    while (i > 0) {
        current = current.next;
    }
    return current;
}

By the way: 顺便说说:

  • The convention for class names is a beginning capital: SllNode . 类名的约定是开头的大写形式: SllNode
  • Do not use fields for things like current and current2 where they can be local variables. 不要将字段用于诸如currentcurrent2可以作为局部变量的字段。

Exchanging nodes, the hard way 交换节点,艰难的方式

Here one has to think, so it is best to deal with special cases first, and then only treat i < j . 这里必须要思考,因此最好先处理特殊情况,然后再处理i < j

public void swap(int i, int j) {
    if (i >= size() || j >= size()) {
        throw new IndexOutOfBoundsException();
    }
    if (i == j) {
        return;
    }
    if (j < i) {
        swap(j, i);
        return;
    }

    // i < j

    sllNode ithPredecessor = null;
    sllNode ithNode = head;
    for (int z = 0; z < i; z++) {
        ithPredecessor = ithNode;
        ithNode = ithNode.next;
    }

    sllNode jthPredecessor = ithNode;
    sllNode jthNode = ithNode.next;
    for (int q = i + 1; q < j; q++) {
        jthPredecessor = jthNode;
        jthNode = jthNode.next;
    }

    // Relink both nodes in the list:

    // - The jthNode:
    if (ithPredecessor == null) {
        head = jthNode;
    } else {
        ithPredecessor.next = jthNode;
    }
    sllNode jNext = jthNode.next;
    //if (ithNode.next == jthNode) {
    if (jthPredecessor == ithNode) {
        jthNode.next = ithNode;
    } else {
        jthNode.next = ithNode.next;
    }

    // - The ithNode:
    if (jthPredecessor == ithNode) {
    } else {
        jthPredecessor.next = ithNode;
    }
    ithNode.next = jNext;
}

No guarantee that the logic is okay. 无法保证逻辑是正确的。 There are tricks: 有技巧:

    //if (ithNode.next == jthNode) {
    if (jthPredecessor == ithNode) {

Both conditions test whether i + 1 == j , but testing on a .next and then assigning makes the condition a momentary state. 这两个条件都测试i + 1 == j ,但是在.next上进行测试然后赋值使该条件成为瞬时状态。 As you see it would have been easier to have one single if (i + 1 == j) { ... } else { ... } and handle both the ithNode and jthNode. 如您所见,如果有一个if (i + 1 == j) { ... } else { ... }并同时处理ithNode和jthNode,那将更容易。

To do this, you need to swap 2 things: the node as next from the previous node, and the next node. 为此,您需要交换两件事:上一个节点的下一个节点和下一个节点。

Once you found current and current2 which are the previous nodes of the nodes you want to swap, do this: 找到要交换的节点的先前节点currentcurrent2 ,请执行以下操作:

Swap the nodes: 交换节点:

sllNode tmp = current.next;
current.next = current2.next;
current2.next = tmp;

Then swap the next: 然后交换下一个:

tmp = current.next.next;
current.next.next = current2.next.next;
current2.next.next = tmp;

// Swapping two elements in a Linked List using Java // 使用 Java 交换链表中的两个元素

import java.util.*;导入 java.util.*;

class SwappingTwoElements { class SwappingTwoElements {

public static void main(String[] args)
{

    LinkedList<Integer> ll = new LinkedList<>();

    // Adding elements to Linked List
    ll.add(10);
    ll.add(11);
    ll.add(12);
    ll.add(13);
    ll.add(14);
    ll.add(15);

    // Elements to swap
    int element1 = 11;
    int element2 = 14;

    System.out.println("Linked List Before Swapping :-");

    for (int i : ll) {
        System.out.print(i + " ");
    }

    // Swapping the elements
    swap(ll, element1, element2);
    System.out.println();
    System.out.println();

    System.out.println("Linked List After Swapping :-");

    for (int i : ll) {
        System.out.print(i + " ");
    }
}

// Swap Function
public static void swap(LinkedList<Integer> list,
                        int ele1, int ele2)
{

    // Getting the positions of the elements
    int index1 = list.indexOf(ele1);
    int index2 = list.indexOf(ele2);

    // Returning if the element is not present in the
    // LinkedList
    if (index1 == -1 || index2 == -1) {
        return;
    }

    // Swapping the elements
    list.set(index1, ele2);
    list.set(index2, ele1);
}

} Output Before Swapping Linked List:- 10 11 12 13 14 15 } Output 在交换链表之前:- 10 11 12 13 14 15

After Swapping Linked List:- 10 14 12 13 11 15 Time Complexity: O(N), where N is the Linked List length交换链表后:- 10 14 12 13 11 15 时间复杂度:O(N),其中 N 是链表长度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM