Java面试编程题-1:反转链表

Java面试编程题-1:反转链表

题目:输入一个链表,反转链表后,输出新链表的表头。

示例1
输入:
{1,2,3}
返回值:
{3,2,1}

1、首先定义单向链表的节点Node

class Node{

    private int data;
    private Node next;

    public int getData() {
        return data;
    }

    public Node getNext() {
        return next;
    }

    public void setData(int data) {
        this.data = data;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public Node(int data){
        this.data = data;
        this.next = null;
    }

}

2、定义链表 Nodelist,包括链表的构造函数 Nodelist(),反转函数 reverse() 和输出函数 prt()

class Nodelist{

    Node head;

    public Nodelist(){
        head = new Node(0);
        for(int i = 10; i > 0; i--){
            Node n = new Node(i);
            n.setNext(head.getNext());
            head.setNext(n);
        }
    }

    public void reverse(){
        Node pre = null;
        Node cur = head;
        Node next = null;
        while(cur != null){
            next = cur.getNext();
            cur.setNext(pre);
            pre = cur;
            cur = next;
        }
        head = pre;
    }

    public void prt(){
        Node p = head;
        while(p != null){
            System.out.print(p.getData() + " ");
            p = p.getNext();
        }
        System.out.println();
    }
}

3、测试函数

public class MyClass {

    public static void main(String[] args){

        Nodelist nl = new Nodelist();
        nl.prt();
        nl.reverse();
        nl.prt();
    }

}

4、输出结果
Java面试编程题-1:反转链表_第1张图片

你可能感兴趣的:(java,面试题,java)