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;
- }
- }
- public class LinkedList {
- public static void main(String arg[]) {
- System.out.println("Program to reverse Linked List.");
- LL l1 = new LL();
- l1.insertAtEnd(1);
- l1.insertAtEnd(2);
- l1.insertAtEnd(3);
- l1.insertAtEnd(4);
- l1.insertAtEnd(5);
- l1.insertAtEnd(6);
- l1.insertAtEnd(7);
- l1.insertAtEnd(8);
- l1.display();
- System.out.println("\nThe linked list after reversing is : ");
- l1.reverse();
- l1.display();
- }
- }
Add Comment
Please, Sign In to add comment