package com.algorithm.collections;
public class LinkedArrayListDemo {
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public static void main(String args[]){ MyLinkedList my = new MyLinkedList(); HeroNode h1 = new HeroNode(1,"A",null); HeroNode h2 = new HeroNode(2,"B",null); HeroNode h3= new HeroNode(3,"C",null); HeroNode h4 = new HeroNode(4,"D",null); my.add(h1); my.add(h2); my.add(h3); my.add(h4); my.print(); HeroNode hn = my.getKthNode(4); if(hn !=null) System.out.println(hn.getName()+":" + hn.getNum());
// HeroNode reverts = my.revert();
// reverts.print(reverts);
复制代码
1
2}
}
class MyLinkedList{
HeroNode head;
public MyLinkedList(){
head = new HeroNode(0,“start”, null);
}
复制代码
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**public void add(HeroNode node){** HeroNode tmpHead = head; while(tmpHead.next !=null){ tmpHead = tmpHead.next; } tmpHead.next =node; } **public void del(HeroNode node){** HeroNode tmpHead = head; while(tmpHead.next !=null){ if(tmpHead.next.getNum() == node.getNum()){ tmpHead.next = tmpHead.next.next; break; } tmpHead = tmpHead.next; } } **public HeroNode getKthNode(int k)**{ if(k<=0) { System.out.println("not correct index,"); return null; } HeroNode hn =head.next; HeroNode hnKthBefore =null; boolean flag = false; int i=1; while(hn !=null){ if(i == k){ hnKthBefore = head.next; //初始化 flag=true; } if(i>k){ hnKthBefore = hnKthBefore.next; } i=i+1; hn = hn.next; } System.out.println("i="+i); System.out.println("k="+k); if(i<=k && flag ==false){ System.out.println("not correct index, it is bigger than the length: "+i); } return hnKthBefore; } **public HeroNode revert()**{ HeroNode revertHead = head; HeroNode tmp1 = null; HeroNode tmp2 = head.next; if(head.next !=null && head.next.next ==null ) return head; while(tmp2 !=null){ HeroNode tmp3 = tmp2.next; tmp2.next = tmp1; tmp1 = tmp2; tmp2 = tmp3; } revertHead.next = tmp1; return revertHead; } public void print(){ HeroNode hn = head; hn.print(hn); }
}
class HeroNode{
private int num;
private String name;
public HeroNode next;
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24public HeroNode(int num, String name, HeroNode next){ this.num = num; this.name = name; this.next = next; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void print(HeroNode hn){ while(hn !=null){ System.out.print("["+hn.getNum()+"-"+hn.getName()+"] => "); hn = hn.next; } }
}
最后
以上就是顺利外套最近收集整理的关于单向链表操作【单链表revert,求取倒数第k个node】的全部内容,更多相关单向链表操作【单链表revert内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复