File tree 1 file changed +71
-0
lines changed
1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ class LinkedList
2
+ {
3
+ Node head ; // head of linked list
4
+
5
+ /* Linked list node */
6
+ class Node
7
+ {
8
+ int data ;
9
+ Node next ;
10
+ Node (int d )
11
+ {
12
+ data = d ;
13
+ next = null ;
14
+ }
15
+ }
16
+
17
+ /* Function to print middle of linked list */
18
+ void printMiddle ()
19
+ {
20
+ Node slow_ptr = head ;
21
+ Node fast_ptr = head ;
22
+ if (head != null )
23
+ {
24
+ while (fast_ptr != null && fast_ptr .next != null )
25
+ {
26
+ fast_ptr = fast_ptr .next .next ;
27
+ slow_ptr = slow_ptr .next ;
28
+ }
29
+ System .out .println ("The middle element is [" +
30
+ slow_ptr .data + "] \n " );
31
+ }
32
+ }
33
+
34
+ /* Inserts a new Node at front of the list. */
35
+ public void push (int new_data )
36
+ {
37
+ /* 1 & 2: Allocate the Node &
38
+ Put in the data*/
39
+ Node new_node = new Node (new_data );
40
+
41
+ /* 3. Make next of new Node as head */
42
+ new_node .next = head ;
43
+
44
+ /* 4. Move the head to point to new Node */
45
+ head = new_node ;
46
+ }
47
+
48
+ /* This function prints contents of linked list
49
+ starting from the given node */
50
+ public void printList ()
51
+ {
52
+ Node tnode = head ;
53
+ while (tnode != null )
54
+ {
55
+ System .out .print (tnode .data +"->" );
56
+ tnode = tnode .next ;
57
+ }
58
+ System .out .println ("NULL" );
59
+ }
60
+
61
+ public static void main (String [] args )
62
+ {
63
+ LinkedList llist = new LinkedList ();
64
+ for (int i =5 ; i >0 ; --i )
65
+ {
66
+ llist .push (i );
67
+ llist .printList ();
68
+ llist .printMiddle ();
69
+ }
70
+ }
71
+ }
You can’t perform that action at this time.
0 commit comments