-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq2p6.java
More file actions
58 lines (56 loc) · 1.41 KB
/
Copy pathq2p6.java
File metadata and controls
58 lines (56 loc) · 1.41 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
public class q2p6{
public static void main(String[] args){
Node head = new Node(1);
head.append(2);
head.append(3);
head.append(4);
head.append(3);
head.append(2);
head.append(1);
Node newHead = head.reverse();
Node buf = newHead;
while(buf != null){
System.out.println(buf.value);
buf = buf.next;
}
System.out.println(compare(head, newHead));
}
public static boolean compare(Node A, Node B){
while(A != null){
if(A.value != B.value)
return false;
A = A.next;
B = B.next;
}
return true;
}
}
// T: O(n)
// S: O(n)
// A: another way, using stack, check first part and second part.
class Node{
public Node next = null;
public int value;
public Node(int value){
this.value = value;
}
public void append(int value){
Node end = new Node(value);
Node previous = this;
while(previous.next != null){
previous = previous.next;
}
previous.next = end;
}
public Node reverse(){
Node oldHead = this;
Node newHead = null;
while(oldHead != null){
Node rnode = new Node(oldHead.value);
oldHead = oldHead.next;
rnode.next = newHead;
newHead = rnode;
}
return newHead;
}
}