java实现单链表反转(遍历方式)

来源:互联网 发布:mac怎么安装打印机驱动 编辑:程序博客网 时间:2024/05/17 03:41

千辛万苦啊!!


public class NodeDemo {public static void main(String[] args){Node head = new Node(0);Node temp = null;Node cur = null;for(int i=1;i<10;i++){temp = new Node(i);if(i==1)head.setNextNode(temp);elsecur.setNextNode(temp);cur = temp;}Node h = head;while(h!=null){System.out.print(h.getData()+",");h = h.getNextNode();}head = reverse(head);System.out.println("");while(head!=null){System.out.print(head.getData()+",");head = head.getNextNode();}}public static Node reverse(Node node){Node pre = node;Node cur = node.getNextNode();Node next;while(cur!=null){next = cur.getNextNode();cur.setNextNode(pre);pre = cur;cur = next;}node.setNextNode(null);return pre;}}class Node{int data;Node next;Node(int data){this.data = data;this.next = null;}public void setNextNode(Node node){this.next = node;}public Node getNextNode(){return next;}public int getData(){return data;}}







0 0
原创粉丝点击