单链表逆序输出

来源:互联网 发布:淘宝朋友代付款 编辑:程序博客网 时间:2024/06/10 04:02

很经典的“单链表逆序”问题,很多公司的面试题库中都有这道题。

public class LianedNode {    class Node{        int data;        Node next;        public Node(int data){            this.data=data;        }    }        public static void main(String[] args) {        // TODO Auto-generated method stub        LianedNode lian=new LianedNode();        Node head,tail;        head=tail=lian.new Node(0);        for(int i=1;i<10;i++){            Node p=lian.new Node(i);            tail.next=p;            //System.out.println(tail.data+""+tail.next.data);            //System.out.println("--------------");            tail=p;            //System.out.println(tail.data+"");        }        tail=head;        while(tail!=null){            //System.out.println(tail.data);            tail=tail.next;        }        head=reverse(head);        while(head!=null){            System.out.println(head.data);            head=head.next;        }    }    private static Node reverse(Node head) {        if(head==null||head.next==null){            return head;        }        Node newhead=null;        Node nextnode;        while(head!=null){            nextnode=head.next;            head.next=newhead;            newhead=head;            head=nextnode;        }        return newhead;    }}
原创粉丝点击