-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListTest.java
More file actions
96 lines (92 loc) · 2.26 KB
/
LinkedListTest.java
File metadata and controls
96 lines (92 loc) · 2.26 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package Idea;
import java.util.Scanner;
class Link{
private class Node{
private int data;
private Node next;
public Node(){
data = 0;
next = null;
}
public Node(int value){
data = value;
next = null;
}
}
private Node headAddr;
private Node searchValueAddr(int value){
Node p = headAddr.next;
while(p != null){
if(p.data == value){
return p;
}
p = p.next;
}
return null;
}
private Node searchPrevAddr(int value){
Node p = headAddr.next;
Node q = headAddr;
while(p != null){
if(p.data == value){
return q;
}
q = p;
p = p.next;
}
return null;
}
public void prtAllValue(){
Node p = headAddr.next;
while(p != null){
System.out.print(p.data+" ");
p = p.next;
}
System.out.println();
}
public Link(){
headAddr = new Node();
headAddr.next = null;
}
public void addValue(int value){
Node addV = new Node(value);
addV.next = headAddr.next;
headAddr.next = addV;
}
public void addValueNonZero(){
Scanner sc = new Scanner(System.in);
for(;;){
int x;
x = sc.nextInt();
if(x == 0) break;
addValue(x);
}
}
public void changeValue(int oldValue,int newValue){
Node p = searchValueAddr(oldValue);
if(p != null) p.data = newValue;
}
public void removeValue(int value){
Node p,q;
p = searchPrevAddr(value);
if(p != null){
q = p.next;
p.next = q.next;
}
}
}
public class LinkedListTest {
public static void main(String[] args) {
Link l1 = new Link();
l1.addValue(2);
l1.addValue(6);
l1.addValue(8);
l1.prtAllValue();
l1.changeValue(2,4);
l1.prtAllValue();
l1.removeValue(4);
l1.prtAllValue();
l1.addValueNonZero();
l1.prtAllValue();
}
}