读书人

[编程兑现单链表逆转][java代码]

发布时间: 2012-12-21 12:03:49 作者: rapoo

[编程实现单链表逆转][java代码]

代码如下,核心的代码在于:

package com.jy.list;public class ReverseList {public static void main(String[] args) {Node head = add(null, "a");add(head, "b");add(head, "c");add(head, "d");add(head, "e");print(head);head = reverse(head);print(head);}public static  Node reverse(Node head) {if(head==null) {return null;}Node p = head;Node q = head.next;p.next=null; //这个必须的~~~,否则链表就成有环的了。while(q!=null) {Node temp = q.next;q.next = p;p = q;q = temp;}return p;}public static  Node add(Node head,String data) {if(head==null) {return new Node(data);} else {Node p = head;while(p.next!=null) {p = p.next;}p.next = new Node(data);return head;}}public static void print(Node head) {if(head==null) {System.out.println("null");}else {Node p = head;while(p!=null) {System.out.print(p.data+"\t");p = p.next;}System.out.print("\n");}}}class Node {public Node(String data2) {this.data = data2;}public String toString() {return data;};String data;Node next;}
?

读书人网 >编程

热点推荐