- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListlastnum.java
More file actions
Latest commit
70 lines (63 loc) · 1.3 KB
/
Copy pathListlastnum.java
File metadata and controls
70 lines (63 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
packagecom.test;
publicclassListlastnum {
/**
* @param args
* 题目:输入带头结点的单链表L,输出该单链表中倒数第k个结点。
* 单链表的倒数第0个结点为该单链表的尾指针。要求只能遍历一次单链表。
*/
publicstaticvoidmain(String[] args) {
//生成链表
nodelist = generatelist();
intk = 0; //查找倒数第k个节点
noden = findlastnode(list,k);
System.out.println("倒数第"+k+"个节点值为"+n.value);
}
privatestaticnodefindlastnode(nodelist, intk) {
nodep = list;
nodeq = list;
if(k<0){
System.out.println("链表太短");
}
if(list == null ){
System.out.println("链表为空");
}
while(k>0){
p = p.next;
k--;
if(p == null ){
System.out.println("链表太短不存在倒数第"+k+"个节点");
}
}
System.out.println(p.value);
while(p.next != null){
p = p.next;
q = q.next;
}
returnq;
}
publicstaticnodegeneratelist() {
//生成链表
noden1 = newnode(1,"a");
noden2 = newnode(2,"b");
noden3 = newnode(3,"c");
noden4 = newnode(4,"d");
noden5 = newnode(5,"e");
noden6 = newnode(6,"f");
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = null;
returnn1;
}
}
classnode1{
intkey;
Stringvalue;
nodenext;
publicnode1(intkey,Stringvalue){
this.key = key;
this.value = value;
}
}