-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked List
66 lines (56 loc) · 2.02 KB
/
Linked List
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
****GFG DSA****
****Linked List Basic Level Question and Solution****
Q1:) Linked List Insertion ---> Basic Level
Create a link list of size N according to the given input literals. Each integer input is accompanied by an indicator which can either be 0 or 1. If it is 0, insert the integer in the beginning of the link list. If it is 1, insert the integer at the end of the link list.
Hint: When inserting at the end, make sure that you handle NULL explicitly.
Example 1:
Input:
LinkedList: 9->0->5->1->6->1->2->0->5->0
Output: 5 2 9 5 6
Explanation:
Length of Link List = N = 5
9 0 indicated that 9 should be
inserted in the beginning. Modified
Link List = 9.
5 1 indicated that 5 should be
inserted in the end. Modified Link
List = 9,5.
6 1 indicated that 6 should be
inserted in the end. Modified Link
List = 9,5,6.
2 0 indicated that 2 should be
inserted in the beginning. Modified
Link List = 2,9,5,6.
5 0 indicated that 5 should be
inserted in the beginning. Modified
Link List = 5,2,9,5,6.
Final linked list = 5, 2, 9, 5, 6.
Expected Time Complexity: O(1) for insertAtBeginning() and O(N) for insertAtEnd().
Expected Auxiliary Space: O(1) for both.
***OUTPUT ==>
class Solution{
public:
//Function to insert a node at the beginning of the linked list.
Node *insertAtBegining(Node *head, int x) {
Node *temp = new Node(x);
temp->next = head;
head = temp;
return head;
}
//Function to insert a node at the end of the linked list.
Node *insertAtEnd(Node *head, int x) {
Node *temp2 = new Node(x);
if(head == NULL){
return temp2;
}
else{
Node *temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = temp2;
temp2->next = NULL;
return head;
}
}
};