不借助栈、数组等额外的空间实现链表的逆序(手动在草稿纸上绘制一下过程,很容易理解)
class MyList{
int val;
MyList next;
public MyList(int val) {
// TODO Auto-generated constructor stub
this.val = val;
this.next = null;
}
}
public class ReverseList {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyList head = new MyList(1);
MyList p = head;
for(int i = 2;i<=10;i++){
p.next = new MyList(i) ;
p = p.next;
}
print(head);
head = reverse(head);//逆序链表
print(head);
}
//逆序链表 过程:遍历链表,将其头结点的next指向新链表的头结点
private static MyList reverse(MyList head) {
MyList newHead = null;
while(head!=null){
MyList p = head.next;//保存链表的next
head.next = newHead;//将head的next指向新的链表头
newHead = head;//将新链表头指向头结点
head = p;//将head赋给之前保存的next
}
return newHead;
}
//打印链表
private static void print(MyList head) {
// TODO Auto-generated method stub
MyList p = head;
while(p!=null){
System.out.print(p.val+" ");
p = p.next;
}
System.out.println();
}
}