剣指offer 13--一方向チェーンテーブルを反転

2071 ワード

タイトル:一方向チェーンテーブルを反転し、元のチェーンテーブルのヘッダノードを入力し、反転後のチェーンテーブルのヘッダノードを返します.
2つの方式を使用して、第1の方式は尾挿法を使用して、新しいチェーンテーブルを創立して、この構想は比較的に明確です
第2の方法は、チェーンテーブル要素を1つずつ逆方向に指すように、順方向ノードを確立することである.
package   offer;

/*  :      ,          ,                 。*/
public class Test16 {
	public static void main(String args[]){
		LinkList head = new LinkList();
        head.value = 1;

        head.next = new LinkList();
        head.next.value = 2;

        head.next.next = new LinkList();
        head.next.next.value = 3;

        head.next.next.next = new LinkList();
        head.next.next.next.value = 4;

        head.next.next.next.next = new LinkList();
        head.next.next.next.next.value = 5;

        head.next.next.next.next.next = new LinkList();
        head.next.next.next.next.next.value = 6;
        
//        LinkList list = reverseList(head);
//        while(list != null){
//        	System.out.print(list.value+"  ");
//        	list = list.next;
//        } 
//        
//        System.out.println();
        
        LinkList list2 = reverseList2(head);
        while(list2 != null){
        	System.out.print(list2.value+"  ");
        	list2 = list2.next;
        } 
	}
	
	public static class LinkList{
		int value;
		LinkList next;
	}
	
	public static LinkList reverseList(LinkList head){
		//      
		LinkList newlist = new LinkList();
		newlist.next = null;
		LinkList next;
		while(head != null){
			next = head.next; //       ,     head.next  
			
			head.next = newlist.next;
			newlist.next = head;//                     
			
			head = next; //            
		}
		return newlist.next;//                    
	}

	public static LinkList reverseList2(LinkList head){
		//          ,           
		LinkList pre = null;      //                
		LinkList current = head;
		while(current != null){
			LinkList next = current.next;
			
			current.next = pre;
			pre = current; //          ,          
			
			current = next;
		}
		return pre; //    pre        ,pre    head
		
	}
}

できたら難しくない,これはくだらない話だ.