牛客题霸--链表中倒数第k个结点
链表中倒数第k个结点
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=117&&tqId=34991&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
牛客题霸题目链接:链表中倒数第k个结点
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=117&&tqId=34991&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
1.使用栈压入,然后取出第k个
public ListNode FindKthToTail(ListNode head,int k) { if(head==null) return null; if(k<=0) return null; Stack<ListNode> st = new Stack<ListNode>(); while(head!=null){ st.push(head); head=head.next; } for(int i=1;i<k;i++){ if(!st.empty()){ st.pop(); }else{ return null; } } if(!st.empty()){ return st.peek(); } return null; }
2.定义快指针和慢指针
快指针先走 k-1 步,到达第 k 个节点。
然后两指针同时齐步走,当快指针到达末尾时,此时慢指针就在倒数第k个节点上
public ListNode FindKthToTail(ListNode head,int k) { if(head==null) return null; if(k<=0) return null; ListNode fast = head; ListNode slow = head; for(int i=1;i<k;i++){ if(fast.next!=null){ fast=fast.next; }else{ return null; } } while(fast.next!=null){ fast=fast.next; slow=slow.next; } return slow; }