-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdelete_first_node.java
53 lines (42 loc) · 958 Bytes
/
delete_first_node.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
/*
ip: 10->20->30->NULL
op: 20->30->40->NULL
ip: 10->NULL
op: NULL
ip: NULL
op: NULL
*/
public class delete_first_node {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
// printing before deleting a node
printList(head);
System.out.println();
head = delHead(head);
// printing after deleting the node
printList(head);
}
static Node delHead(Node head) {
if (head == null)
return head;
else
return head.next;
}
public static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
}
}
/*
in java, we do not have to worry about memory de-allocation
in c++:
Node* temp = head->next;
delete head
return temp;
Time: O(1)
*/