Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package chapter_4_linked_list;
- public class SortedLinkedList {
- private Node head;
- public void insertInSortedList(int data) {
- Node newNode = new Node(data);
- if(this.head == null) {
- this.head = newNode;
- }
- Node current = this.head;
- if(current.getNextNode() == null) {
- current.setNextNode(newNode);
- return;
- }
- while(current != null) {
- if(current.getData() < newNode.getData() && current.getNextNode().getData() > newNode.getData()) {
- newNode.setNextNode(current.getNextNode());
- current.setNextNode(newNode);
- current = current.getNextNode();
- }
- }
- }
- @Override
- public String toString() {
- String list = "{ ";
- /**
- * Create a new node which will be the current node set it as the head
- * element as we have to start from the head element
- */
- Node currentNode = this.head;
- // to go through all the nodes till the current node points to null
- while (currentNode != null) {
- // get the data of the current node from the toString of the Node
- // class
- list += currentNode.toString() + ", ";
- // then we set / increase the currentNode as the next node until it
- // reaches null
- currentNode = currentNode.getNextNode();
- }
- list += " }";
- return list;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment