剑指offer_链表中倒数第k个结点

题目描述

输入一个链表,输出该链表中倒数第k个结点。

方法一就是暴力法,遍历出最后第k个结点

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode FindKthToTail(ListNode head,int k) {
12         if(head==null) return null;
13         int num=0;
14         ListNode cur =head;
15         while(cur.next!=null){
16             num++;
17             cur=cur.next;
18         }
19         num++;
20         int count = num-k+1;
21         cur =head;
22         while(cur.next!=null){
23             count--;
24             if(count==0) return cur;
25             cur=cur.next;
26            
27         }
28         if(count==1) return cur;
29         return null;
30     }
31 }

方法二

设链表的长度为 N。设置两个指针 P1 和 P2,先让 P1 移动 K 个节点,则还有 N - K 个节点可以移动。此时让 P1 和 P2 同时移动,可以知道当 P1 移动到链表结尾时,P2 移动到第 N - K 个节点处,该位置就是倒数第 K 个节点。

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode FindKthToTail(ListNode head,int k) {
12         if(head==null) return null;
13         
14         ListNode p1 =head;
15         while(p1!=null&&k-->0){
16             p1=p1.next;
17         }
18         if(k>0) return null;
19         ListNode p2 =head;
20         while(p1!=null){
21             p1=p1.next;
22             p2=p2.next;
23         }
24         
25         return p2;
26         
27     }
28 }

 

posted @ 2019-08-25 10:35  chyblogs  阅读(120)  评论(0)    收藏  举报