29
loading...
This website collects cookies to deliver better user experience
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
next = null;
}
}
public Node head = null;
public Node tail = null;
public void addNode(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public void display() throws IllegalStateException {
Node current = head;
if (head == null) {
throw new IllegalStateException("Your List is empty");
}
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
public Node reverse(Node start) throws IllegalStateException {
if (start == null) {
throw new IllegalStateException("List is empty");
}
Node current = start;
Node prev = null;
while (current != null) {
Node next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
public static int arr(Node start) throws IllegalStateException {
Node current = start;
if (start == null) {
throw new IllegalStateException("Your List is empty");
}
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.data);
current = current.next;
}
String str = sb.toString();
int x = Integer.parseInt(str);
return x; // string converted to int
}
public static void main(String[] args) {
// creating two demo lists
AddTwoNumbers list1 = new AddTwoNumbers();
list1.addNode(1);
list1.addNode(1);
list1.addNode(6);
AddTwoNumbers list2 = new AddTwoNumbers();
list2.addNode(1);
list2.addNode(9);
list2.addNode(2);
// reversing the lists
Node x1 = list1.reverse(list1.head);
Node x2 = list2.reverse(list2.head);
// getting the returned integer representation of the lists
int y1 = arr(x1);
int y2 = arr(x2);
// adding both the values that's why we did the 5th step to simplify this summing process
int sum = y1 + y2;
// convert again to string builder so that we can reverse it easily
StringBuilder str = new StringBuilder();
StringBuilder output = str.append(sum).reverse();
// create a new list that will be returned
AddTwoNumbers finalList = new AddTwoNumbers();
// pass the values to the list
for (int i = 0; i < output.length(); i++) {
int x =Integer.parseInt(String.valueOf(output.charAt(i)));
finalList.addNode(x);
}
// and, finally display it
finalList.display();
}