- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinklistreverse.java
More file actions
Latest commit
60 lines (53 loc) · 1.14 KB
/
Copy pathLinklistreverse.java
File metadata and controls
60 lines (53 loc) · 1.14 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
packagecom.test;
publicclassLinklistreverse {
/**
* @param args
* 单链表逆置
*/
publicstaticvoidmain(String[] args) {
//生成链表
nodelist = generatelist();
//链表逆置
nodenewlist = reverse(list);
//新链表的第一个应该是逆置前的最后一个
System.out.println(newlist.value);
}
privatestaticnodereverse(nodelist) {
//如果链表为空,或者只有一个元素返回
if(list == null || list.next == null ){
returnlist;
}
// 链表逆置
nodepre = null; //指向当前节点的前一个节点
nodecur = list ; //指向当前节点
nodenext = list; //指向当前节点的下一个节点
while(cur!= null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
returnpre;
}
publicstaticnodegeneratelist() {
//生成链表
noden1 = newnode(1,"a");
noden2 = newnode(2,"b");
noden3 = newnode(3,"c");
noden4 = newnode(4,"d");
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = null;
returnn1;
}
}
classnode{
intkey;
Stringvalue;
nodenext;
publicnode(intkey,Stringvalue){
this.key = key;
this.value = value;
}
}