Java 实现单链表反序
孤风一剑
8月 07, 2014
221

-
- public class SingleLinkedListReverse {
-
- 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.setNext(temp);
- } else {
- cur.setNext(temp);
- }
- cur = temp;
- }
-
- Node h = head;
- while (h != null) {
- System.out.print(h.getData() + “\t”);
- h = h.getNext();
- }
- System.out.println();
-
-
-
-
-
-
-
-
-
- h = Node.reverse1(head);
- while (h != null) {
- System.out.print(h.getData() + “\t”);
- h = h.getNext();
- }
-
-
- }
- }
-
-
-
-
- class Node {
- Object data;
- Node next;
-
- Node(Object d) {
- this.data = d;
- }
- Node(Object d, Node n) {
- this.data = d;
- this.next = n;
- }
- public Object getData() {
- return data;
- }
- public void setData(Object data) {
- this.data = data;
- }
- public Node getNext() {
- return next;
- }
- public void setNext(Node next) {
- this.next = next;
- }
-
- static Node reverse1(Node head) {
-
- Node p = null;
- Node q = head;
-
- while (head.next != null) {
- p = head.next;
- head.next = p.next;
- p.next = q;
- q = p;
- }
- return p;
-
- }
-
- static Node reverse2(Node head) {
-
- Node p1 = head, p2 = head.next, p3;
-
- while (p2 != null) {
- p3 = p2.next;
- p2.next = p1;
- p1 = p2;
- p2 = p3;
- }
- head.next = null;
- return p1;
- }
- }