Java链接列表交换最后和第一个元素

时间:2018-03-31 11:51:23

标签: java

我经常与链表挣扎,我想尝试交换第一个元素和最后一个元素。我的代码并没有真正起作用,我试图找到错误。我知道结构有问题,我首先想写一个方法但是方法没有得到任何输出....所以我只是在main方法中写了所有内容....

public class Node {
    int key;
    Node next;

    public static void main(String[] args) {
        Node x = new Node();
        Node t = new Node();
        Node head = t;              // Ersten Knoten erschaffen
        t.key = 1;                  // Wert (1) setzen
        x = t;       

        for (int i=2; i<=10; i++) {
            t.next = new Node();    // Letztes Element zeigt auf neuen Knoten
            t = t.next;             // Temp-Knoten t auf neues Element
            t.key = i;              // Inhalt des neuen Elements setzen
        }
        while (t.next != null) {
            t = t.next;
        }
        System.out.println(head);
    }
}

我得到以下输出:Node@232204a1

1 个答案:

答案 0 :(得分:0)

这样的东西?

class Playground {
    public static void main(String[ ] args) {
        LinkedList l = new LinkedList(new int[]{1, 2, 3, 4, 5, 6, 7});
        System.out.println(l); // Prints: 1 | 2 | 3 | 4 | 5 | 6 | 7 |
        l.swapFirstAndLast();
        System.out.println(l); // Prints: 7 | 2 | 3 | 4 | 5 | 6 | 1 | 
    }
}

class LinkedList {

    private Node head;

    public LinkedList(int[] startValues) {
        head = new Node(startValues[0]);

        Node current = head;

        for (int i=1; i<startValues.length; i++) {
            current.next = new Node(startValues[i]);
            current = current.next;
        }
    }

    public void swapFirstAndLast() {
        Node current = head;
        Node beforeLast = null;

        while(current.next != null) {
            beforeLast = current;
            current = current.next;
        }

        current.next = head.next;
        head.next = null;
        beforeLast.next = head;
        head = current;
    }

    public String toString() {
        StringBuilder stb = new StringBuilder();
        Node current = head;

        while(current != null) {
            stb.append("" + current.key);
            stb.append(" | ");
            current = current.next;
        }

        return stb.toString();
    }
}

class Node {
    public Node next;
    public int key;

    public Node(Node next, int key) {
        this.next = next;
        this.key = key;
    }

    public Node(int key) {
        this.key = key;
    }
}