-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathAddStart.java
More file actions
47 lines (45 loc) · 1.35 KB
/
AddStart.java
File metadata and controls
47 lines (45 loc) · 1.35 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
35
36
37
38
39
40
41
42
43
44
45
46
47
package linkedlist;
import java.util.Scanner;
public class AddStart {
public static void main(String[] args) {
Node<Integer> head = takeInput();
Node<Integer> newHead = addStart(head,10);
print(newHead);
}
public static Node<Integer> addStart(Node<Integer> head,int data){
Node<Integer> newNode = new Node<>(data);
newNode.next = head;
head = newNode;
return head;
}
public static Node<Integer> takeInput(){
Node<Integer> head = null;
Node<Integer> tail = null;
Scanner sc = new Scanner(System.in);
int data = sc.nextInt();
while(data!=-1){
Node<Integer> newNode = new Node<>(data);
if(head == null){
head = newNode;
tail = newNode;
}else{
// Node<Integer> temp = head;
// while(temp.next!=null){
// temp = temp.next;
// }
// temp.next = newNode;
tail.next = newNode;
tail = newNode;
}
data = sc.nextInt();
}
return head;
}
public static void print(Node<Integer> head){
Node<Integer> temp = head;
while(temp!=null){
System.out.print(temp.data+" ");
temp = temp.next;
}
}
}