Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /**
- * Created by MOHIT on 24-01-2018.
- */
- class node{
- public int element;
- public node link;
- //constructor that accepts only element
- node(int element) {
- this.element = element;
- this.link = null;
- }
- //constructor that accepts both link and element
- node(int element, node link){
- this.element = element;
- this.link = link;
- }
- //method to update the element
- void updateData(int element){
- this.element = element;
- }
- //method to update or setup link
- void updateLink(node link){
- this.link = link;
- }
- //method to get the element from the node
- int getElement(){
- return this.element;
- }
- //method to get the next node
- node getNextNode(){
- return this.link;
- }
- }
- class LL {
- Scanner sc = new Scanner(System.in);
- node head;
- void insertAtStart(int number){
- node newNode = new node(number);
- if(head == null){
- head = newNode;
- } else {
- newNode.updateLink(head);
- }
- head = newNode;
- return;
- }
- void insertAtEnd(int element){
- if(head == null){
- this.insertAtStart(element);
- return;
- }
- node current = this.head;
- while(current.getNextNode() != null){
- current = current.getNextNode();
- }
- node newNode = new node(element);
- current.updateLink(newNode);
- return;
- }
- void display(){
- node current = this.head;
- while(current!= null){
- System.out.print(current.getElement());
- if(current.getNextNode() != null){
- System.out.print("-->");
- }
- current = current.getNextNode();
- }
- }
- // function to reverse k starting nodes from the linked list
- // function to reverse linked list
- void reverse(){
- if(this.head == null){
- return;
- }
- node nextNode = null;
- node prev = null;
- node current = this.head;
- while(current != null){
- nextNode = current.getNextNode();
- current.updateLink(prev);
- prev = current;
- current = nextNode;
- }
- this.head = prev;
- }
- void addOne(){
- this.reverse();
- addingOneUtil();
- this.reverse();
- }
- // adding one to linked list
- private void addingOneUtil(){
- int carry = 1;
- int sum = 0;
- node start = this.head;
- while(start != null && carry != 0){
- sum = start.getElement() + carry;
- start.updateData(sum % 10);
- carry = sum / 10;
- start = start.getNextNode();
- }
- if(carry != 0){
- this.insertAtEnd(carry);
- }
- }
- }
- public class LinkedList {
- public static void main(String arg[]) {
- System.out.println("Program to add one to a number represented by Linked List.");
- LL l1 = new LL();
- l1.insertAtEnd(9);
- l1.insertAtEnd(9);
- l1.insertAtEnd(9);
- l1.insertAtEnd(9);
- l1.insertAtEnd(9);
- l1.insertAtEnd(9);
- l1.insertAtEnd(9);
- l1.insertAtEnd(9);
- l1.display();
- System.out.println("\nNumber after adding one is : ");
- l1.addOne();
- l1.display();
- }
- }
Add Comment
Please, Sign In to add comment