需要4个指针,当前节点,前一个节点,后一个节点和尾节点(新头),当前节点不断后移,不断把next执行前一个
class listnode{
int data;
listnode next;
}
public class reverse {
public static void main(String args[]){int[] n={1,3,5,7,9,11,13,15,17};
//int[] a={1,2,3,4,5,6,7,8,9};
//reorder(a);
//for(int each:a){
// System.out.print(each+" ");
//}
listnode list=CreateList(n);
listnode revlist=reverse(list);
print(revlist);
}
public static listnode CreateList(int[] n){
listnode head=new listnode();
head.data=n[0];
head.next=null;
listnode point=head;
for(int i=1;i<n.length;i++){
listnode node=new listnode();
node.data=n[i];
node.next=null;
point.next=node;
point=point.next;
}
return head;
}
public static void print(listnode l){
while(l!=null){
System.out.print(l.data+" ");
l=l.next;
}
}
public static listnode reverse(listnode list){
listnode tail=null;listnode node=list;
listnode pre=null;
while(node!=null){
listnode next=node.next;
if(next==null)
tail=node;
node.next=pre;
pre=node;
node=next;
}
return tail;
}
}