Is it possible to write a binary search tree in C without pointers?
I have written using pointers as follows.
Working BST code in C using pointers
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node* left;
struct node* right;
}Node;
Node* root = NULL;
int insert(int);
int display(Node*);
int main(void)
{
int n = 0;
while(1)
{
printf("Enter data : ");
scanf("%d",&n);
if(n == -1)
break;
insert(n);
}
display(root);
return 0;
}
int insert(int data)
{
Node* node = malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
Node* parent;
Node* trav;
if(root == NULL)
root = node;
else
{
trav = root;
while(trav != NULL)
{
parent = trav;
if(node->data < trav->data)
trav = trav->left;
else
trav = trav->right;
}
if(node->data < parent->data)
parent->left = node;
else
parent->right = node;
}
}
int display(Node* node)
{
if(node == NULL)
return 0;
display(node->left);
printf("%d ",node->data);
display(node->right);
}
Is is possible to write a BST without pointers, and using Nodes only. So, I want to access the left as node.left instead of node->left and so on. Even the members of the structure node should be like
typedef struct node
{
int data;
struct node left;
struct node right;
}Node;
and the Node members would be declared as
Node root; Node node;
and not as
Node* root; Node* node;
If it's not possible to write BST using the above structures, why is it so? Is it because, NULL is a pointer which has a value reserved for indicating that the pointer does not refer to a valid object. So, if we were using just a structure, we wouldn't know when to stop. So, I commented out the NULL lines in the above code, and made changes to access as structure members and not pointers. I was expecting it to atleast compile, although it would be an infinite loop at places. However, it gives me some compilation errors as well.
Tried BST code in C without using pointers, does not compile
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int data;
struct node left;
struct node right;
}Node;
//Node root = NULL;
Node root;
int insert(int);
int display(Node);
int rootformed = 0;
int main(void)
{
int n = 0;
while(1)
{
printf("Enter data : ");
scanf("%d",&n);
if(n == -1)
break;
insert(n);
}
display(root);
return 0;
}
int insert(int data)
{
Node node = malloc(sizeof(Node));
node.data = data;
node.left = NULL;
node.right = NULL;
Node parent;
Node trav;
if(rootformed == 0)
{
root = node;
rootformed = 1;
}
else
{
trav = root;
//while(trav != NULL)
while(1)
{
parent = trav;
if(node.data < trav.data)
trav = trav.left;
else
trav = trav.right;
}
if(node.data < parent.data)
parent.left = node;
else
parent.right = node;
}
}
int display(Node node)
{
//if(node == NULL)
//return 0;
display(node.left);
printf("%d ",node.data);
display(node.right);
}
However, I was going through how a binary search tree is implemented in Java, as follows. As seen below, members are accessed using the dot symbol. I'm curious to understand how it's done here.
If class is a structure, can I say that an object is a pointer to the
structure. The only difference being that in C, a pointer to a
structure uses the notation -> to access the internal members of the
structure, whereas, an object just uses . to access the internal
memebers of the structure(class)
Working BST code in java, which uses the . notation, got me thinking on how I can emulate this in C to use the . symbol and not ->
public class BinarySearchTree
{
public Node root;
public BinarySearchTree()
{
this.root = null;
}
public boolean find(int id)
{
Node current = root;
while(current!=null)
{
if(current.data == id)
{
return true;
}
else if(id < current.data)
{
current = current.left;
}
else
{
current = current.right;
}
}
return false;
}
public boolean delete(int id)
{
Node parent = root;
Node current = root;
boolean isLeftChild = false;
while(current.data != id)
{
parent = current;
if(id < current.data)
{
isLeftChild = true;
current = current.left;
}
else
{
isLeftChild = false;
current = current.right;
}
if(current ==null)
{
return false;
}
}
//if i am here that means we have found the node
//Case 1: if node to be deleted has no children
if(current.left==null && current.right==null)
{
if(current==root)
{
root = null;
}
if(isLeftChild ==true)
{
parent.left = null;
}
else
{
parent.right = null;
}
}
//Case 2 : if node to be deleted has only one child
else if(current.right==null)
{
if(current==root)
{
root = current.left;
}
else if(isLeftChild)
{
parent.left = current.left;
}
else
{
parent.right = current.left;
}
}
else if(current.left==null)
{
if(current==root)
{
root = current.right;
}
else if(isLeftChild)
{
parent.left = current.right;
}
else
{
parent.right = current.right;
}
}
else if(current.left!=null && current.right!=null)
{
//now we have found the minimum element in the right sub tree
Node successor = getSuccessor(current);
if(current==root)
{
root = successor;
}
else if(isLeftChild)
{
parent.left = successor;
}
else
{
parent.right = successor;
}
//successor.left = current.left;
}
return true;
}
public Node getSuccessor(Node deleteNode)
{
Node successsor =null;
Node successsorParent =null;
Node current = deleteNode.right;
while(current!=null)
{
successsorParent = successsor;
successsor = current;
current = current.left;
}
//check if successor has the right child, it cannot have left child for sure
//if it does have the right child, add it to the left of successorParent.
//successsorParent
if(successsor!=deleteNode.right)
{
successsorParent.left = successsor.right;
successsor.right = deleteNode.right;
}
if(successsor==deleteNode.right)
{
/* Then no more right tree */
}
successsor.left = deleteNode.left;
return successsor;
}
public void insert(int id)
{
Node newNode = new Node(id);
if(root==null)
{
root = newNode;
return;
}
Node current = root;
Node parent = null;
while(true)
{
parent = current;
if(id < current.data)
{
current = current.left;
if(current==null)
{
parent.left = newNode;
return;
}
}
else
{
current = current.right;
if(current==null)
{
parent.right = newNode;
return;
}
}
}
}
public void display(Node root)
{
if(root != null)
{
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static void main(String arg[])
{
BinarySearchTree b = new BinarySearchTree();
b.insert(3);b.insert(8);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(15);b.insert(16);
System.out.println("Original Tree : ");
b.display(b.root);
System.out.println("");
System.out.println("Check whether Node with value 4 exists : " + b.find(4));
System.out.println("Delete Node with no children (2) : " + b.delete(2));
b.display(root);
System.out.println("\n Delete Node with one child (4) : " + b.delete(4));
b.display(root);
System.out.println("\n Delete Node with Two children (10) : " + b.delete(10));
b.display(root);
}
}
class Node
{
int data;
Node left;
Node right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
In stead of pointers to memory objects, you can allocate a large array of Node objects and store indexes into this array in the left and right members.
Array entry 0 is the root node. You must keep track of the first unused array element to store a new Node. You can use calloc to allocate the array and realloc to enlarge the array.
You must keep track of deleted items: keep track of the first one and put in left the index of the next deleted item (kind of linked list). You can also keep track of the last deleted item to quickly append another deleted iem to the list.
You can implement binary search in an array, using array indexes instead of pointers. In C the array is just a language construct that automates pointer arithmetic and keeps it out of your code. If you malloc the entire array of structs and make the left and right members integers of some appropriate size, it can work.
But in structs created individually with malloc you can't do it without pointers because...
In C the structure is just memory allocated in a contiguous block. The . operator translates to a simple offset from the beginning of a block.
When you try to use the . operator to refer to .left or .right you are referring to a different struct that you created with a different malloc and it could be anywhere in heap memory. So the simple offset from the beginning of the current node is unknown.
So in C you need a pointer, to store the address of the left or right node.
In Java these are object references, essentially nicely wrapped and managed pointers. The JVM is managing allocation and tracking memory addresses, and this is mostly transparent to your code. You are, in effect, using pointers in the Java code, at run-time but your source code is written in terms of object references.
You could also implement binary search in C using a file or memory mapped file, using offsets into that file instead of C pointers. This is probably not what you intend in your question, but is/was often done in applications with large sorted data sets that need binary search.
Related
I am having trouble figuring out how to set a variable "minData" to the minimum value inserted into a binary search tree. If I am thinking of this correctly, the most minimum value in the tree will always be in the left subtree so my code for setting this minimum value should go under the "else if (root.data < data)" statement. I also don't know how to access the minData variable inside my insert method. My code so far is:
private class Node {
int key;
int data;
int minData;
private Node left;
private Node right;
private Node root;
Node(int data) {
this.data = data;
left = null;
right = null;
root = null;
}
}
public TheBST(Node root) {
root = null;
}
public void insert(Node root, int data) {
Node newNode = new Node(data);
if(root == null) {
Node node = new Node(data);
root = node;
}
else if(root.data > data) {
if(root.left == null) {
Node node = new Node(data);
root.left = node;
}
insert(root.left, data);
}
else if(root.data < data) {
if(root.right == null) {
Node node = new Node(data);
root.right = node;
return;
}
insert(root.right, data);
}
}
Your forming of BST is not accurately done. You need to return from the method (or stack fragment of memory in case recursive procedure) when you would actually find the place to insert.
Add the return statement for the left-subtree:
else if(root.data > data) {
if(root.left == null) {
Node node = new Node(data);
root.left = node;
return;
}
insert(root.left, data);
}
Which is you are doing in case of the right-subtree.
P.S: once you are done with tree insertion, you can return the left-most-node from left-subtree, it would have the minimum value.
Here is my Node class:
private class Node {
private int key; // the key field
private Object data; // the rest of the data item
private Node left; // reference to the left child/subtree
private Node right; // reference to the right child/subtree
private Node parent; // reference to the parent
.. and so on.
This is the inorder iterator with next() and hasNext() methods:
private class inorderIterator implements LinkedTreeIterator {
private Node nextNode;
private inorderIterator() {
// The traversal starts with the root node.
nextNode = root;
if(nextNode == null)
return;
while (nextNode.left != null)
nextNode = nextNode.left;
}
public boolean hasNext() {
return (nextNode != null);
}
public int next() {
if(!hasNext())
throw new NoSuchElementException();
Node r = nextNode;
if (nextNode.right != null) {
nextNode = nextNode.right;
while (nextNode.left != null) {
nextNode = nextNode.left;
}
return r.key;
} else while (true) {
if (nextNode.parent == null) {
nextNode = null;
return r.key;
}
if (nextNode.parent.left == nextNode) {
nextNode = nextNode.parent;
return r.key;
}
nextNode = nextNode.parent;
}
return r.key;
}
}
The problem is, it only ever prints the left nodes on the left sub-tree.
For example, for a tree with root node 17, left node 15 and right node 19, it only prints 15.
So it never enters a right subtree.
I'm guessing the problem is with the else while (true) portion, but I can't figure out how to fix this.
You could try a recursive approach.
Something like:
public void printTreeInOrder(Node node){
if(node.left != null){
printTree(node.left);
}
System.out.println(node.key);
if(node.right != null){
printTree(node.right);
}
}
If you passed this method the root node it should print out the entire tree for you.
I hope this helps.
Best.
Turns out that the parent field of my nodes was not being updated properly. Once that was fixed, the iterator worked properly.
I would use a stack with this helper method:
Node advance_to_min(Node r)
{
while (r.left != null)
{
s.push(r);
r = r.left;
}
return r;
}
The first node inorder is given by the call to this method on the root. Something like:
curr = advance_to_min(curr);
And then I would implement next() thus:
void next()
{
curr = curr.right;
if (curr != null)
{
curr = advance_to_min(curr);
return;
}
if (s.is_empty())
curr = null;
else
curr = s.pop();
}
curr and the stack s would be iterator attributes. curr would point to the current node in the inorder sequence.
The cost O(lg n) at worst case for each next() call (if the tree tends to be balanced) and the approach does not require parent pointers; so, it would have the same space cost than using parent pointers but only in the worst case
I have written a code to insert an element in a binary tree in java. Here are the functions to do the same:
public void insert(int data)
{
root = insert(root, data);
}
private Node insert(Node node, int data)
{
if (node == null)
node = new Node(data);
else
{
if (node.getRight() == null)
node.right = insert(node.right, data);
else
node.left = insert(node.left, data);
}
return node;
}
However when I traverse the tree, the answer I get is wrong. Here are the traversal functions (preorder):
public void preorder()
{
preorder(root);
}
private void preorder(Node r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
Okay so as suggested here's the definition for the Node class:
public class Node {
public int data;
public Node left, right;
/* Constructor */
public Node() {
left = null;
right = null;
data = 0;
}
/* Constructor */
public Node(int d, Node l, Node r) {
data = d;
left = l;
right = r;
}
//Constructor
public Node(int d) {
data = d;
}
/* Function to set link to next Node */
public void setLeft(Node l) {
left = l;
}
/* Function to set link to previous Node */
public void setRight(Node r) {
right = r;
}
/* Function to set data to current Node */
public void setData(int d) {
data = d;
}
/* Function to get link to next node */
public Node getLeft() {
return left;
}
/* Function to get link to previous node */
public Node getRight() {
return right;
}
/* Function to get data from current Node */
public int getData() {
return data;
}
}
I have re-checked the algorithm for traversal many times, and it's working perfectly. I believe the problem is in the insertion algorithm. Any suggestions?
If I understood correctly, you want to fill your binary tree in "layers". E.g. you want to put something into depth 4 only if depth 3 is "full binary tree".
Then the problem is whole logic of your insert algorithm that is DFS-based. In other words it inserts elements deeper and deeper on the one side instead of building full binary tree on both sides.
If you look closer to your insert algorithm you will see that once you skip "right" subtree, you will never return to it - even if the "left" subtree is already full binary tree. That leads to the tree that will be growing deeper and deeper on the left side but not growing on the right side.
Speaking in programming language. You do:
(node.right != null) && (node.left != null) => insert (node.left)
but you can't do this (start inserting node.left). What if node.left has both children and node.right has no children? You will attempt to insert to the left even you should do it in node.right.
So what you really need to do insertion BFS-based. That means you will traverse the tree for insertion "in layers". Queue should be your new friend here:-) (not the stack/recursion):
public void insert(int data) {
if (root == null) {
root = new Node(data);
return;
}
Queue<Node> nodesToProcess = new LinkedList<>();
nodesToProcess.add(root);
while (true) {
Node actualNode = nodesToProcess.poll();
// Left child has precedence over right one
if (actualNode.left == null) {
actualNode.left = new Node(data);
return;
}
if (actualNode.right == null) {
actualNode.right = new Node(data);
return;
}
// I have both children set, I will process them later if needed
nodesToProcess.add(actualNode.left);
nodesToProcess.add(actualNode.right);
}
}
Your method returns given node, but your method has to return inserted node which is node.right or node.left
I have a ordered binary tree:
4
|
|-------|
2 5
|
|-------|
1 3
The leaves point to null. I have to create a doubly link list which should look like
1<->2<->3<->4<->5
(Obviously 5 should point to 1)
The node class is as follows:
class Node {
Node left;
Node right;
int value;
public Node(int value)
{
this.value = value;
left = null;
right = null;
}
}
As you can see the doubly link list is ordered (sorted) as well.
Question: I have to create the linked list form the tree without using any extra pointers. The left pointer of the tree should be the previous pointer of the list and the right pointer of the tree should be the next pointer of the list.
What I thought off: Since the tree is an ordered tree, the inorder traversal would give me a sorted list. But while doing the inorder traversal I am not able to see, where and how to move the pointers to form a doubly linked list.
P.S I checked some variations of this question but none of them gave me any clues.
It sounds like you need a method that accepts a Node reference to the root of the tree and returns a Node reference to the head of a circular list, where no new Node objects are created. I would approach this recursively, starting with the simple tree:
2
|
|-----|
1 3
You don't say whether the tree is guaranteed to be full, so we need to allow for 1 and/or 3 being null. The following method should work for this simple tree:
Node simpleTreeToList(Node root) {
if (root == null) {
return null;
}
Node left = root.left;
Node right = root.right;
Node head;
if (left == null) {
head = root;
} else {
head = left;
left.right = root;
// root.left is already correct
}
if (right == null) {
head.left = root;
root.right = head;
} else {
head.left = right;
right.right = head;
right.left = root;
}
return head;
}
Once it is clear how this works, it isn't too hard to generalize it to a recursive method that works for any tree. It is a very similar method:
Node treeToList(Node root) {
if (root == null) {
return null;
}
Node leftTree = treeToList(root.left);
Node rightTree = treeToList(root.right);
Node head;
if (leftTree == null) {
head = root;
} else {
head = leftTree;
leftTree.left.right = root;
root.left = leftTree.left;
}
if (rightTree == null) {
head.left = root;
root.right = head;
} else {
head.left = rightTree.left;
rightTree.left.right = head;
rightTree.left = root;
root.right = rightTree;
}
return head;
}
If I got all the link assignments covered correctly, this should be all you need.
Do an in-order traversal of the list, adding each list item to the doubly linked list as you encounter it. When done, add an explicit link between the first and last items.
Update 3/6/2012: Since you must reuse the Node objects you already have, after you put the node objects into the the list, you can then iterate over the list and reset the left and right pointers of the Node objects to point to their siblings. Once that is done, you can get rid of the list and simply return the first node object.
This should also work:
NodeLL first = null;
NodeLL last = null;
private void convertToLL(NodeBST root) {
if (root == null) {
return;
}
NodeLL newNode = new NodeLL(root.data);
convertToLL(root.left);
final NodeLL l = last;
last = newNode;
if (l == null)
first = newNode;
else {
l.next = newNode;
last.prev = l;
}
convertToLL(root.right);
}
Let your recursion return the left and right end of formed list. Then you link your current node to the last of the left list, and first of the right list. Basic case it, when there is no left or right element, which is the node it self for both. Once all is done, you can link the first and last of the final result. Below is the java code.
static void convertToSortedList(TreeNode T){
TreeNode[] r = convertToSortedListHelper(T);
r[1].next = r[0];
r[0].prev= r[1];
}
static TreeNode[] convertToSortedListHelper(TreeNode T){
TreeNode[] ret = new TreeNode[2];
if (T == null) return ret;
if (T.left == null && T.right == null){
ret[0] = T;
ret[1] = T;
return ret;
}
TreeNode[] left = TreeNode.convertToSortedListHelper(T.left);
TreeNode[] right = TreeNode.convertToSortedListHelper(T.right);
if (left[1] != null) left[1].next = T;
T.prev = left[1];
T.next = right[0];
if (right[0] != null) right[0].prev = T;
ret[0] = left[0]==null? T:left[0];
ret[1] = right[1]==null? T:right[1];
return ret;
}
Add the following method to your Node class
public Node toLinked() {
Node leftmost = this, rightmost = this;
if (right != null) {
right = right.toLinked();
rightmost = right.left;
right.left = this;
}
if (left != null) {
leftmost = left.toLinked();
left = leftmost.left;
left.right = this;
}
leftmost.left = rightmost;
rightmost.right = leftmost;
return leftmost;
}
EDIT By maintaining the invariant that the list returned by toLinked() has the proper form, you can easily get the left- and rightmost nodes in the sublist returned by the recursive call on the subtrees
/* input: root of BST. Output: first node of a doubly linked sorted circular list. **Constraints**: do it in-place. */
public static Node transform(Node root){
if(root == null){
return null;
}
if(root.isLeaf()){
root.setRight(root);
root.setLeft(root);
return root;
}
Node firstLeft = transform(root.getLeft());
Node firstRight = transform(root.getRight());
Node lastLeft = firstLeft == null ? null : firstLeft.getLeft();
Node lastRight= firstRight == null ? null : firstRight.getLeft();
if(firstLeft != null){
lastLeft.setRight(root);
root.setLeft(lastLeft);
if(lastRight == null){
firstLeft.setLeft(root);
}
else{
firstLeft.setLeft(lastRight);
root.setRight(firstRight);
}
}
if(firstRight != null){
root.setRight(firstRight);
firstRight.setLeft(root);
if(lastLeft == null){
root.setLeft(lastRight);
lastRight.setLeft(root);
firstLeft = root;
}
else{
root.setLeft(lastLeft);
lastRight.setRight(firstLeft);
}
}
return firstLeft;
}
I am implementing my own linked list in Java. The node class merely has a string field called "name" and a node called "link". Right now I have a test driver class that only inserts several names sequentially. Now, I am trying to write a sorting method to order the nodes alphabetically, but am having a bit of trouble with it. I found this pseudocode of a bubblesort from someone else's post and tried to implement it, but it doesn't fully sort the entries. I'm not really quite sure why. Any suggestions are appreciated!
private void sort()
{
//Enter loop only if there are elements in list
boolean swapped = (head != null);
// Only continue loop if a swap is made
while (swapped)
{
swapped = false;
// Maintain pointers
Node curr = head;
Node next = curr.link;
Node prev = null;
// Cannot swap last element with its next
while (next != null)
{
// swap if items in wrong order
if (curr.name.compareTo(next.name) < 0)
{
// notify loop to do one more pass
swapped = true;
// swap elements (swapping head in special case
if (curr == head)
{
head = next;
Node temp = next.link;
next.link = curr;
curr.link = temp;
curr = head;
}
else
{
prev.link = curr.link;
curr.link = next.link;
next.link = curr;
curr = next;
}
}
// move to next element
prev = curr;
curr = curr.link;
next = curr.link;
}
}
}
I spent some minutes eyeballing your code for errors but found none.
I'd say until someone smarter or more hard working comes along you should try debugging this on your own. If you have an IDE like Eclipse you can single-step through the code while watching the variables' values; if not, you can insert print statements in a few places and hand-check what you see with what you expected.
UPDATE I
I copied your code and tested it. Apart from the fact that it sorts in descending order (which may not be what you intended) it worked perfectly for a sample of 0, 1 and 10 random nodes. So where's the problem?
UPDATE II
Still guessing what could be meant by "it doesn't fully sort the entries." It's possible that you're expecting lexicographic sorting (i.e. 'a' before 'B'), and that's not coming out as planned for words with mixed upper/lower case. The solution in this case is to use the String method compareToIgnoreCase(String str).
This may not be the solution you're looking for, but it's nice and simple. Maybe you're lazy like I am.
Since your nodes contain only a single item of data, you don't really need to re-shuffle your nodes; you could simply exchange the values on the nodes while leaving the list's structure itself undisturbed.
That way, you're free to implement Bubble Sort quite simply.
you should use the sorting procedures supplied by the language.
try this tutorial.
Basically, you need your element class to implement java.lang.Comparable, in which you will just delegate to obj.name.compareTo(other.name)
you can then use Collections.sort(yourCollection)
alternatively you can create a java.util.Comparator that knows how to compare your objects
To obtain good performance you can use Merge Sort.
Its time complexity is O(n*log(n)) and can be implemented without memory overhead for lists.
Bubble sort is not good sorting approach. You can read the What is a bubble sort good for? for details.
This may be a little too late. I would build the list by inserting everything in order to begin with because sorting a linked list is not fun.
I'm positive your teacher or professor doesn't want you using java's native library. However that being said, there is no real fast way to resort this list.
You could read all the nodes in the order that they are in and store them into an array. Sort the array and then relink the nodes back up. I think the Big-Oh complexity of this would be O(n^2) so in reality a bubble sort with a linked list is sufficient
I have done merge sort on the singly linked list and below is the code.
public class SortLinkedList {
public static Node sortLinkedList(Node node) {
if (node == null || node.next == null) {
return node;
}
Node fast = node;
Node mid = node;
Node midPrev = node;
while (fast != null && fast.next != null) {
fast = fast.next.next;
midPrev = mid;
mid = mid.next;
}
midPrev.next = null;
Node node1 = sortLinkedList(node);
Node node2 = sortLinkedList(mid);
Node result = mergeTwoSortedLinkedLists(node1, node2);
return result;
}
public static Node mergeTwoSortedLinkedLists(Node node1, Node node2) {
if (null == node1 && node2 != null) {
return node2;
} else if (null == node2 && node1 != null) {
return node1;
} else if (null == node1 && null == node2) {
return null;
} else {
Node result = node1.data <= node2.data ? node1 : node2;
Node prev1 = null;
while (node1 != null && node2 != null) {
if (node1.data <= node2.data) {
prev1 = node1;
node1 = node1.next;
} else {
Node next2 = node2.next;
node2.next = node1;
if (prev1 != null) {
prev1.next = node2;
}
node1 = node2;
node2 = next2;
}
}
if (node1 == null && node2 != null) {
prev1.next = node2;
}
return result;
}
}
public static void traverseNode(Node node) {
while (node != null) {
System.out.print(node + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
MyLinkedList ll1 = new MyLinkedList();
ll1.insertAtEnd(10);
ll1.insertAtEnd(2);
ll1.insertAtEnd(20);
ll1.insertAtEnd(4);
ll1.insertAtEnd(9);
ll1.insertAtEnd(7);
ll1.insertAtEnd(15);
ll1.insertAtEnd(-3);
System.out.print("list: ");
ll1.traverse();
System.out.println();
traverseNode(sortLinkedList(ll1.start));
}
}
The Node class:
public class Node {
int data;
Node next;
public Node() {
data = 0;
next = null;
}
public Node(int data) {
this.data = data;
}
public int getData() {
return this.data;
}
public Node getNext() {
return this.next;
}
public void setData(int data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
#Override
public String toString() {
return "[ " + data + " ]";
}
}
The MyLinkedList class:
public class MyLinkedList {
Node start;
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (start == null) {
start = newNode;
return;
}
Node traverse = start;
while (traverse.getNext() != null) {
traverse = traverse.getNext();
}
traverse.setNext(newNode);
}
public void traverse() {
if (start == null)
System.out.println("List is empty");
else {
Node tempNode = start;
do {
System.out.print(tempNode.getData() + " ");
tempNode = tempNode.getNext();
} while (tempNode != null);
System.out.println();
}
}
}