-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay15-Linked-List
More file actions
35 lines (25 loc) · 1.27 KB
/
Day15-Linked-List
File metadata and controls
35 lines (25 loc) · 1.27 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
Problem:
Objective
Today we're working with Linked Lists. Check out the Tutorial tab for learning materials and an instructional video!
A Node class is provided for you in the editor. A Node object has an integer data field, data , and a Node instance pointer,next,
pointing to another node (i.e.: the next node in a list).
A Node insert function is also declared in your editor. It has two parameters: a pointer, head, pointing to the first
node of a linked list, and an integer data value that must be added to the end of the list as a new Node object.
Task
Complete the insert function in your editor so that it creates a new Node (pass data as the Node constructor argument)
and inserts it at the tail of the linked list referenced by the head parameter.
Once the new node is added, return the reference to the head node.
Note: If the head argument passed to the insert function is null, then the initial list is empty.
Solution:
public static Node insert(Node head,int data) {
if(head == null){
head = new Node(data);
return head;
}
Node last = head;
while(last.next != null) {
last = last.next;
}
last.next = new Node(data);
return head;
}