14.連結串列中倒數第k個結點
阿新 • • 發佈:2018-12-19
題目描述
輸入一個連結串列,輸出該連結串列中倒數第k個結點。題目解答
方法一:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head,int k) { if(head==null || k<1){return null; } ListNode cur=head; while(cur!=null){ k--; cur=cur.next; } if(k>0){ //1->2->3,k=4,k的變化:3,2,1,大於0,沒有倒數第k個節點 return null; }else if(k==0){ //1->2->3,k=3,k的變化:2,1,0,等於0,就是頭節點 returnhead; }else{ //k<0,1->2->3,k=2,k的變化:1,0,-1,小於0 cur=head; while(++k!=0){ cur=cur.next; } return cur.next; } } }
方法二:
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head,int k) { if(head==null || k<1){ return null; } ListNode pre=head;//快指標 ListNode last=head;//慢指標 for(int i=1;i<k;i++){ if(pre.next!=null){//快指標先走k步 pre=pre.next; }else{ return null; } } while(pre.next!=null){//當快指標走到頭的時候,慢指標指向倒數第k個節點 pre=pre.next; last=last.next; } return last; } }
快慢指標