N14-输出倒数第K个节点

题目描述

输入一个链表,输出该链表中倒数第k个结点。
 1 /**
 2  * 输入一个链表,输出该链表中倒数第k个结点。
 3  * @author Sonya
 4  *思路一:新建一个栈,将链表中所有节点一次压入栈中,然后弹出k次栈,第K次即为倒数第K个节点。(这个太麻烦了需要建立栈)
 5  *思路二:先遍历一遍,得出总的节点数目。然后到节点n-k处 下一处即为倒数第k个节点。
 6  *
 7  *
 8  */
 9 /*//这个类已经被定义过了此处不用再定义一遍
10  * class ListNode {
11     int val;
12     ListNode next = null;
13 
14     ListNode(int val) {
15         this.val = val;
16     }
17 }
18  */
19 
20 
21 public class N14_FindKthToTail {
22     
23      public ListNode FindKthToTail(ListNode head,int k) {
24          if(head==null)return head;
25          int count=0;
26          ListNode p;
27          for(p=head;p!=null;p=p.next) {
28               count++;
29          }
30          if(count<k)return null;
31          p=head;
32          for(int i=1;i<=count-k;i++) {
33              p=p.next;
34          }         
35         return p;
36 
37         }
38     
39 
40     public static void main(String[] args) {
41         // TODO Auto-generated method stub
42         N14_FindKthToTail n14=new N14_FindKthToTail();
43         ListNode listNode=new ListNode(1);
44         ListNode L2=new ListNode(2);
45         ListNode L3=new ListNode(3);
46         ListNode L4=new ListNode(4);
47         ListNode L5=new ListNode(5);
48         listNode.next=L2;
49         L2.next=L3;
50         L3.next=L4;
51         L4.next=L5;
52         ListNode p;
53         p=n14.FindKthToTail(listNode, 1);
54         System.out.println(p.val);
55     }
56 
57 }

猜你喜欢

转载自www.cnblogs.com/kexiblog/p/11075529.html
今日推荐