public class Solution {
static class Node {
char data;
Node next;
public Node() {
}
public Node(char data, Node next) {
this.data = data;
this.next = next;
}
}
public static Node init() {
Node n5 = new Node('E', null);
Node n4 = new Node('D', n5);
Node n3 = new Node('C', n4);
Node n2 = new Node('B', n3);
Node n1 = new Node('A', n2);
return n1;
}
public static Node reverse(Node head) {
Node curr = head;
Node pre = null;
while (curr != null) {
Node next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
public static Node reverse2(Node head) {
Node dummyHead = new Node();
Node p = head;
while (p != null) {
Node q = p.next;
p.next = dummyHead.next;
dummyHead.next = p;
p = q;
}
return dummyHead.next;
}
public static Node reverse3(Node head) {
if (head == null || head.next == null) {
return head;
}
Node newHead = reverse3(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public static void print(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] args) {
print(reverse(init()));
print(reverse2(init()));
print(reverse3(init()));
}
}
单链表逆转
于 2016-04-27 23:50:53 首次发布