-
Notifications
You must be signed in to change notification settings - Fork 0
/
p177.java
92 lines (80 loc) · 2.32 KB
/
p177.java
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
/*Write a Java program that prompts the user to enter the size of the doubly linked list and the elements of the list. The program then constructs the doubly linked list based on the user input.
Next, the program displays the elements of the doubly linked list in both forward and backward directions.
Test Case 1:
Input:
Enter the size: 5
Enter the elements: 10 20 30 40 50
Expected Output:
Doubly linked list in forward direction:
10 20 30 40 50
Doubly linked list in backward direction:
50 40 30 20 10
Test Case 2:
Input:
Enter the size: 3
Enter the elements: 1 2 3
Expected Output:
Doubly linked list in forward direction:
1 2 3
Doubly linked list in backward direction:
3 2 1*/
import java.util.Scanner;
class Node {
int data;
Node next;
Node prev;
public Node(int d) {
data = d;
next = null;
prev = null;
}
}
class DLL_forward_backward {
static Node hptr = null;
static Node tptr = null;
public static void append(int d) {
if (hptr == null) {
Node temp = new Node(d);
hptr = tptr = temp;
} else {
Node temp = hptr;
while (temp.next != null) {
temp = temp.next;
}
Node nptr = new Node(d);
temp.next = nptr;
nptr.prev = temp;
tptr = nptr;
}
}
public static void forwardDisplay(Node hptr) {
Node temp = hptr;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void backwardDisplay(Node tptr) {
Node temp = tptr;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.prev;
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size");
int n = sc.nextInt();
System.out.println("Enter the elements");
for (int i = 0; i < n; i++) {
int ele = sc.nextInt();
append(ele);
}
System.out.println("Doubly linked list in forward direction: ");
forwardDisplay(hptr);
System.out.println("Doubly linked list in backward direction: ");
backwardDisplay(tptr);
}
}