N14- output of the penultimate node K

Title Description

Input a linked list, the linked list output reciprocal k-th node.
1  / ** 
2  * a list input, the output of the inverse of the k th node in the linked list.
3  * @author Sonya
 4  * a thought: to create a new stack, all the nodes in a linked list onto the stack, then pop the stack k times, the first time K K is the penultimate node. (This is too cumbersome need to build a stack)
 5  * two ideas: first traversal again, to obtain the total number of nodes. Then at the next node nk is the reciprocal of the k-th node.
6  *
 7  *
 8   * / 
9  / * // This class has not been defined the redefinition here again
 10  * {class ListNode
 . 11      int Val;
 12 is      ListNode Next = null;
 13 is  
14      ListNode (int Val) {
 15          the this Val = .val;
 16      }
 . 17  }
 18 is   * / 
. 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 }

 

Guess you like

Origin www.cnblogs.com/kexiblog/p/11075529.html