反轉單鏈表

今天在中金所面試遇到了到簡單但是卻沒重視的題目,結果寫的像坨shi一樣,回來再寫一遍吧,基本思路就是倒轉指針,用一個輔助指針先記錄下來後驅,總共需要三個輔助指針,代碼如下:
public class Size {
	class No{
		public int data;
		public No next;

		public No() {
			// TODO Auto-generated constructor stub
			data = 0;
			next = null;
		}
	}
	
	private No head;
	
	Size(){
		buildList();
	}
	
	public void buildList(){
		head = new No();
		head.data = 0;
		No cur = head;
		for(int i = 0; i < 10;i++){
			No newNode = new No();
			newNode.data = i+1;
			cur.next = newNode;
			cur = newNode;
		}
	}
	
	void reverse(){
		No pre,cur,lat;
		pre = head;
		cur = head.next;
		while(cur!=null){
			lat = cur.next;
			cur.next = pre;
			pre = cur;
			cur = lat;
		}
		head.next = null;
		head = pre;
	}
	
	public void showAll(){
		No pNo = head;
		while(pNo!=null){
			System.out.print(pNo.data);
			pNo = pNo.next;
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		Size size = new Size();
		size.showAll();
		size.reverse();
		size.showAll();
		size.reverse();
		size.showAll();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章