java 實作單連結清單反轉:
class node{
int data;
node next;
public node(int data){
this.data=data;
this.next=null;
}
}
public class lianbiao {
public static void main(String[] args) {
// TODO Auto-generated method stub
int []arr= {,,,,,};
node p,fore,pnext;
node head=new node(arr[]); //head 為第一個節點
p=head;
//建構連結清單
for(int i=;i<arr.length;i++){
p.next=new node(arr[i]);
p=p.next;
}
//輸對外連結表
p=head;
while(p!=null){
System.out.print(p.data+" ");
p=p.next;
}
//連結清單反轉時,需要用到上一個節點fore 和下一個節點pnext。
//目前節點p 重新指向p的上一個節點之前,需要先記錄下p的下一個節點。因為p.next改變後,
//你已經無法通過p.next獲得下一個節點。
p=head;
fore=null;
while(p.next!=null){ //開始反轉
pnext=p.next;//記錄下一個節點
p.next=fore; //p.next反轉 指向前一個節點
fore=p; //更新 fore
p=pnext; //更新p
}
p.next=fore;
System.out.println(" ");
//輸出反轉連結清單
while(p!=null){
System.out.print(p.data+" ");
p=p.next;
}
}
}
結果顯示:
2 5 3 4 1 0
0 1 4 3 5 2