題目描述
解題方法1
public class Test {
public static void main(String[] args) throws Exception {
int[] arr = {10,20,30,40,50};
Node head = create(arr);
reverse(head);
for(Node p = head.next;p!=null;p=p.next){
System.out.println(p.val);
}
}
public static Node reverse(Node head){
if(head==null || head.next==null){
return head;
}
Node p = head.next;
head.next = null;
while(p!=null){
Node temp = p.next;
p.next = head.next;
head.next = p;
p=temp;
}
return head;
}
public static Node create(int[] arr){
Node head = new Node(0);
Node newnode = null;
Node tail = head;
for(int a:arr){
newnode = new Node(a);
newnode.next = tail.next;
tail.next = newnode;
tail = newnode;
}
return head;
}
}
class Node{
int val;
Node next;
Node(int val){
this.val = val;
}
}