1. 程式人生 > >劍指offer——(6)從尾到頭列印連結串列&&反轉連結串列&&連結串列倒數第K個結點

劍指offer——(6)從尾到頭列印連結串列&&反轉連結串列&&連結串列倒數第K個結點

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
		//ListNode head = null;
		ArrayList<Integer> AL = new ArrayList<Integer>();
			public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {		    			    			    	
		    	if(listNode==null) return AL;
		    	//System.out.println("listNode:"+listNode.val);		    										    	
		        int count=1;
		        ListNode ln = listNode;
		        while(ln.next!=null){	
		            count++;
		            ln = ln.next;		            
		        }
		        int arr[] = new int[count];
		        /*arr[count-1] = in2.val;
		        in2 = in2.next;*/
		        while(listNode!=null){		
		            arr[count-1] = listNode.val;		                  
		            if(listNode.next==null) break;
		            listNode = listNode.next;
		            count--;
		        }		        
		        for(Integer i=0;i<arr.length;i++){
		            AL.add(arr[i]);		            
		        }
		        return AL;
	}
}

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.ArrayList;
public class Solution {
		ListNode head = null;
		ArrayList<Integer> AL = new ArrayList<Integer>();
		public ListNode ReverseList(ListNode listNode) {		    			    			    		    										    	
			head = listNode;
	        while(head!=null){	
	            AL.add(head.val);
	            head = head.next;		            
	        }
	        int count = AL.size()-1;
            ListNode temp = null;
	        for(int i = count;i>=0;i--) {	
	        	listNode.val = AL.get(i);
                if(i==count) temp = listNode;
	        	listNode = listNode.next;		            
	        }
			return temp;
	}
}

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode listNode,int k) {
        if(listNode==null) return listNode;
        int count = 0;			    			    			    		    										    	
        ListNode head = listNode;
        while(head!=null){	
            count++;
            head = head.next;		            
        }	     
        if(k>count) return null;
        for(int i = 0;i<count-k;i++) {	
            listNode = listNode.next; 	        	
        }		        
        return listNode;
    }
}