Linked Lists. Head and Tail References - java

Im trying to make an Add and Delete method to my linked list class. I made 2 references with the names Head and Tail.
Head -> 1 -> 2 -> 3 -> Tail:null
I keep getting problems when I try and delete specific nodes because Java says I'm out of bounds. I think it is because my Head isn't pointing to the first Node? What do you guys think? Or am i going about this the total wrong way...
public class LinkedList{
private Node head;
private Node tail;
private int listCount;
public LinkedList()
{
head = new ListNode(null);
tail = new ListNode(null);
listCount = 0;
}
public void add(Object elem){
ListNode newNode = new ListNode(elem);
if (size() == 0){
newNode = head;
tail = head;
}
newNode.setLink(tail);
tail = newNode;
listCount++;
}
public Object delete(int index)
// post: removes the element at the specified position in this list.
{
// if the index is out of range, exit
if(index < 1 || index > size())
throw new IndexOutOfBoundsException();
ListNode current = head;
for(int i = 1; i < index; i++)
{
if(current.getLink() == null)
throw new IndexOutOfBoundsException();
current = current.getLink();
}
current.setLink(current.getLink().getLink());
listCount--; // decrement the number of elements variable
return current.getInfo();
}
public int size() {
return listCount;
}
}
public class Node {
private Node link;
private Object info;
public Node(Object info)
{
this.info = info;
link = null;
}
public void setInfo(Object info)
{
this.info = info;
}
public Object getInfo()
{
return info;
}
public void setLink(Node link)
{
this.link = link;
}
public Node getLink()
{
return link;
}
}

I think it's because your head never links to anything. What I would do to fix it is in your add method, check the size of your list; if it's 0, set the head to the new element and set the tail equal to the head. If it's 1, link the head to the new node and set tail. If it's 2, just set the tail's link to the new node and set the tail (like you have now).
Also, I'm not sure how you implemented it, but newNode.setLink(tail); seems wrong...the tail should be linked to newNode. From the way it looks, it seems like you're trying to do newNode -> tail
EDIT: Ok, here is why I would try
public void add(Object elem){
ListNode newNode = new ListNode(elem);
if (size() == 0){
newNode = head;
tail = head;
}else if(size() == 1){
head.setLink(newNode);
tail = newNode;
}else{
tail.setLink(newNode);
tail = newNode;
}
listCount++;
}

Looks like you did not initialize the link from head to tail when you set up your initial (empty) linked list.
Ok. Here is a strategy to use when working with singly linked lists (forward link only). You need to determine what actions will be allowed on the list (e.g. add/remove from head or tail only?; or add and remove nodes anywhere in the linked list (bringing the list back together once you have cut a node out). If you will be allowing nodes to be deleted from anywhere, then you will need to have a way of UNIQUELY identifying each node (so you can unambiguously determine the node that will be deleted). You may also want to be able to add a node before or after some other node . and uniqueness may be needed for that. If you do NOT care which value you delete or add before/after then you can relax the uniqueness constraint.
Now for strategy to implement. Start with a head (initially null).
To add a node, walk down your linked list until you find a null next link. Replace that with your node, and have your nodes forward link set to null. (Efficiency improvement, have a tail that always has the last node in the linked list, or null if there is nothing in the list).
To delete a node, walk your list until you find the node you want to delete, change the previous link to the link in the node to be deleted (you are now done)
To add a node at the end of the list, go to the link pointed to by tail (if null, list is emplty); change its link to your node, ensure your new node has a null in its link; and set the tail to your node
To count size of linked list, either walk your tree and count (or, for computational efficiency, keep a running size that is incremented or decremented when you add or delete a node.
Does this help?
Look at this link for a full description!

Related

Algorithm: Merge Sort with linked list missing items

I am trying to sort my linked list with merge sort. The list is actually sorted but it is kind of missing first item(s).
Merge sort functions:
public Node mergeSort(Node head) {
if (head == null || head.next == null) {
return head;
}
Node middle = middleElement(head);
Node nextofMiddle = middle.next;
middle.next = null;
return merge(mergeSort(head), mergeSort(nextofMiddle));
}
public Node merge(Node left, Node right) {
Node temp = new Node();
Node newHead = temp;
while (left != null && right != null) {
if (left.info <= right.info) {
temp.next = left;
temp = left;
left = temp.next;
} else {
temp.next = right;
temp = right;
right = temp.next;
}
}
temp.next = (left == null) ? right : left;
return newHead;
}
public Node middleElement(Node head) {
if (head == null) {
return head;
}
Node slow = head;
Node fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
So I printed the list to the screen using traverse:
public static void main(String[] args) {
MyLinkedList mll = new MyLinkedList();
mll.insert(3);
mll.insert(5);
mll.insert(9);
mll.insert(1);
mll.insert(8);
mll.insert(7);
mll.insert(2);
mll.mergeSort(mll.head);
mll.traverse();
}
I have result like this:
1 and 2 missing!
After checking, i noticed that the "tail" of the linked list value is still 2. I don't know why can someone help?. I'm really new to programming so sorry for any inconvenience. Thank you for reading!
You're not far from a correct solution. I was able to get a working sort by adding 1 line and changing 3.
Your merge isn't doing what you think it is.
Allocating a false head node (what you call temp, not a good choice of name; try falseHead) is a fine idea. Then falseHead.next is the true head. That's what you'll finally return as the sorted list. Note that initially it's null, which is what you'd expect.
What you're missing is a variable tail to reference the current last node in the merged list. Since there is initially no last node at all, this should be initialized equal to falseHead. Consequently, when you append the first element to the tail of the current result by setting tail.next, you'll also be setting falseHead.next, i.e. creating the head element. It all works out.
Now, what is the logic for, say, removing the current head of the right list and appending it to the merge result? It's just 3 steps:
Do the append operation by making tail.next the current head of right.
Update tail to tail.next.
Remove the head of right by updating right to right.next.
Of course the left side is similar.
Good luck. You're close.
You have a couple problems that I can see. One, mentioned by #rcgldr, in the comments is that you merge method is returning the temp node newHead, but that node was no value and is not part of your graph. You need to return it's child newHead.next.
The other problem is that you never reset the head of your list. So after all the sorting, the head of mll still points to the original head, which in this case is 3. So when you traverse the list you skip 1 and 2. I'm not sure what your linked list class looks like but something like this should be close -- just assign the final node returned by mergeSort to the head of the list. Then when you traverse you should be starting in the right spot:
mll.head = mll.mergeSort(mll.head);
mll.traverse();

linked list java refernce

I got a linked list java implementation.But one part i dont understand.my class is
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
and i have a fn to insert
public static Node insert(Node head,int data) {
Node current = head;
if(head!=null){
while(current.next!=null){
current = current.next;
}
current.next = new Node(data);
return head;
} else {
return head=new Node(data);
}
}
the thing i dont understand is ,first we set the head to a current variable.
and passing next node to the current object for traversal.
My question how it works, since current has ref of head, so when you assign another value technically you are changing head. i could see that with int data.if i update current.data to 0 then i see head is get affected..
may be it is a below par question but please help me to understand whats happening here...
Basically this function is adding new element as a HEAD element of the linked list collection. Every element has a reference to a NEXT element, so it traverses as long as next element does not exist and then it sets it to the new element (having the data that you passed to the function).
I'm not sure if I understand your concerns, but by changing "current" variable, you are simply changing the "reference" to an object, not changing objects themselves. So you just change the reference as long as the next item does not exist and then you create a new object and set is as referenced by former head (and this object becomes a new head)
I rearranged the code, to make it easier to understand, and added comments :
/**
*Insert a leaf node in a linked list
*#param head represents the head node of the list.
*#return the head node
*/
public static Node insert(Node head,int data) {
//if head does not exist, create it and return it
if (head==null) {
return head=new Node(data);
}
else{//head exist
//search for the end of the linked list (leaf, has no next node)
Node current = head;
while(current.next!=null){
current = current.next;
}
//at the end of loop the current.next == null (leaf)
//add new node as leaf
current.next = new Node(data);
return head; //return head unchanged
}
}
I hope it help to clarify.
When you are assigning a certain node (not just value) to the current node, you are NOT changing that certain node. Here, you have assigned head to be the current node. But that does not mean both nodes are now the same. They are still different. The head node will always have the same value UNTIL someone specifically types head = [enter another node here], assigning a different node to the head node. In Java, = means assignment and == means equals. So assignment and equals are two different concepts.
Example Singly Linked List: 1 -> 2 -> 3 -> NULL
(we know head = Node(1))
Now, suppose user calls insert(head, 4)?
Execution steps:
Node current = head, so current == Node(1) and head == Node(1) (current and head are two different nodes, but with same values for now)
head is null, so execute statements in if statement
current.next == Node(2) so it's not null. Execute statement in while loop
current = current.next so current is assigned Node(2)
current.next == Node(3) so it's not null. Execute statement in while loop
current = current.next so current is assigned Node(3)
current.next == NULL, so stop while loop
current.next = new Node(4), so we assigned Node(4) to current.next
Now we return list starting at head. And head = Node(1) still.
Result : 1 -> 2 -> 3 -> 4 -> NULL

How do you traverse to the end of a linked list? [duplicate]

Here's what I have:
public class Node{
Object data;
Node next;
Node(Object data, Node next){
this.data = data;
this.next = next;
}
public Object getData(){
return data;
}
public void setData (Object data){
this.data = data;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
}
How do I write the code to add a Node at the end of a list?
So if I had
head -> [1] -> [2] -> null
How do I get to
head -> [1] -> [2] -> [3] -> null
Actually...I'm not even sure if I have to add to the end. I think it's valid to add and then sort? Not sure.
Thanks!
public void addToEnd(Object data){
Node temp = this;
while(temp.next!=null)temp=temp.next;
temp.next=new Node(data, null);
}
It's a linked list. You either have to
A) iterate through all your nodes starting at the head, find the last node, then add one.
or
B) keep track of the tail, add to the tail, then update tail to the new last node.
Start from the head:
Node currentNode = headNode;
while (node.getNext() != null) {
currentNode = currentNode.getNext();
}
currentNode.setNext(newNodeForInsertion);
A faster way is to store the last node of the list somewhere so you don't have to go through the whole list.
Recursively navigate through each node until you hit the end.
public void navigate(Node insertNode)
{
if(next == null)
next = insertNode;
else
next.navigate(insertNode);
}
To add to the end, you'd have to walk to the end of the list (i.e., to where next=null) and add a new node there.
In the real world, you'd use an ArrayList for this and not bother with a linked list or manual structure at all.
In your method to add a node, write a while loop that starts at the head and looks to see if the "next node" is null. If it is not, advance to the "next node" and repeat.
Once you are at the node that points to nothing, adding the node is as simple as reassigning the null reference to the node to be added.
A recursive solution:
public void addToEnd(Object data){
if (next==null)
next = new Node(data, null);
else
next.addToEnd(data);
}
Node n = head;
while(n.getNext() != null){
n = n.getNext();
}
n.setNext(nodeToAdd);
That's not sorted, which I can't tell from your question if you want it sorted. Which opens up another whole can of worms such as what do you want to sort on, if you have a linked list of type Object there isn't really anything meaningful to sort on.

given a node how can I find previous node in a singly linked list

Given the current node, how can I find its previous node in a Singly Linked List. Thanks. Logic will do , code is appreciated. We all know given a root node one can do a sequential traverse , I want to know if there is a smarter way that avoids sequential access overhead. (assume there is no access to root node) Thanks.
You can't.
Singly-linked lists by definition only link each node to its successor, not predecessor. There is no information about the predecessor; not even information about whether it exists at all (your node could be the head of the list).
You could use a doubly-linked list.
You could try to rearrange everything so you have the predecessor passed in as a parameter in the first place.
You could scan the entire heap looking for a record that looks like a predecessor node with a pointer to your node. (Not a serious suggestion.)
If you want to delete the current node, you can do that without finding previous node as well.
Python Code:
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next
# Delete Node in a Linked List
Walk through the list from the beginning until you meet a node whose next link points you your current node.
But if you need to do this, perhaps you oughtn't be using a singly linked list in the first place.
Your only option for a singly-linked list is a linear search, something like below (Python-like pseudo code):
find_previous_node(list, node):
current_node = list.first
while(current_node.next != null):
if(current_node.next == node):
return current_node
else:
current_node = current_node.next
return null
Assuming that you're talking about a forward singly linked list (each node only has a pointer to 'next' etc) you will have to iterate from the start of the list until you find the node that has 'next' equal to your current node. Obviously, this is a slow O(n) operation.
Hope this helps.
Keep two-pointer(curr, prev) initially both will point to head of the list.
do a loop on the list until you either reach at the end of the list or at the required node.
for each iteration move curr node to the next of it but before moving to next store its pointer in prev pointer.
prev = curr; // first store current node in prev
curr = curr->next // move current to next
at the end of loop prev node will contain previous node.
getPrev(head, key) {
Node* curr = head;
Node* prev = head;
while(curr !=null && curr->data==key){
prev = curr;
curr = curr->next
}
return prev
}
Example:
list = 1->5->10->4->3
We want prev node of 4 So key = 4 and head point at 1 here
initially:
temp will point to 1
prev will point to 1
iteration 1:
First, assign prev=temp (prev point to 1)
move temp; temp->next (temp point to 5)
iteration 2:
First, assign prev=temp (prev point to 5)
move temp; temp->next (temp point to 10)
iteration 3:
First, assign prev=temp (prev point to 10)
move temp; temp->next (temp point to 4)
iteration 4:
temp->data == key so it will return out of loop.
return prev node
This is some kind of hack which I found out while solving the problem(Delete every even node in a list)
internal void DeleteNode(int p)
{
DeleteNode(head, p);
}
private void DeleteNode(Node head, int p)
{
Node current = head;
Node prev = null;
while (current.next != null)
{
prev = current;
current = current.next;
if (current.data == p)
{
prev.next = current.next;
}
}
}
Now here, in prev you assign the current and then move the current to next thereby prev contains the previous node.
Hope this helps...
You can do it like this.. you can replace the value of current node by value of next node.. and in the next of 2nd last node you can put null. its like delete a element from a string. here is code
void deleteNode(ListNode* node) {
ListNode *pre=node;
while(node->next)
{
node->val=node->next->val;
pre=node;
node=node->next;
}
pre->next=NULL;
}
Use a nodeAt() method and pass the head,size and the index of the current node.
public static Node nodeAt(Node head,int index){
Node n=head;
for(int i=0;i<index;i++,n=n.next)
;
return n;
}
where n returns the node of the predecessor.
Here is a small trick with linear search: just pass in the node or its position whose previous node you are searching for:
private MyNode findNode(int pos) {
//node will have pos=pos-1
pos-- = 1;
MyNode prevNode = null;
int count = 0;
MyNode p = first.next; // first = head node, find it however you want.
//this is for circular linked list, you can use first!=last for singly linked list
while (p != first) {
if (count == pos) {
prevNode = p;
break;
}
p = p.next;
count++;
}
return prevNode;
}
We can traverse through the LinkedList using slow and fast pointers.
Let's say
fast pointer fast = fast.next.next
slow pointer slow = slow.next
Slow pointer will be always a previous of the fast pointer, and so we can able to find it.
It can possible to deleteNode if only given node not root or head. How ?
It can achieve by reversing value in node
4-> 2 -> 1 -> 9 given 2 as node to remove. as above other can't access previous node which is correct because singly linked list we don't store predecessor. What can do is swap value of next of give node to given node and change link to next of next of give node
nextNode = node.next // assigning given node next to new pointer
node.val = nextNode.val // replacing value of given node to nextNode value
node.next = nextNode.next // changing link of given node to next to next node.
I tried this approach and its working fine.
assuming you are using forward singly linked list your code should look like
while(node)
{
previous = node
node = node.next
// Do what ever you want to do with the nodes
}

Java - add a node to the end of a list?

Here's what I have:
public class Node{
Object data;
Node next;
Node(Object data, Node next){
this.data = data;
this.next = next;
}
public Object getData(){
return data;
}
public void setData (Object data){
this.data = data;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
}
How do I write the code to add a Node at the end of a list?
So if I had
head -> [1] -> [2] -> null
How do I get to
head -> [1] -> [2] -> [3] -> null
Actually...I'm not even sure if I have to add to the end. I think it's valid to add and then sort? Not sure.
Thanks!
public void addToEnd(Object data){
Node temp = this;
while(temp.next!=null)temp=temp.next;
temp.next=new Node(data, null);
}
It's a linked list. You either have to
A) iterate through all your nodes starting at the head, find the last node, then add one.
or
B) keep track of the tail, add to the tail, then update tail to the new last node.
Start from the head:
Node currentNode = headNode;
while (node.getNext() != null) {
currentNode = currentNode.getNext();
}
currentNode.setNext(newNodeForInsertion);
A faster way is to store the last node of the list somewhere so you don't have to go through the whole list.
Recursively navigate through each node until you hit the end.
public void navigate(Node insertNode)
{
if(next == null)
next = insertNode;
else
next.navigate(insertNode);
}
To add to the end, you'd have to walk to the end of the list (i.e., to where next=null) and add a new node there.
In the real world, you'd use an ArrayList for this and not bother with a linked list or manual structure at all.
In your method to add a node, write a while loop that starts at the head and looks to see if the "next node" is null. If it is not, advance to the "next node" and repeat.
Once you are at the node that points to nothing, adding the node is as simple as reassigning the null reference to the node to be added.
A recursive solution:
public void addToEnd(Object data){
if (next==null)
next = new Node(data, null);
else
next.addToEnd(data);
}
Node n = head;
while(n.getNext() != null){
n = n.getNext();
}
n.setNext(nodeToAdd);
That's not sorted, which I can't tell from your question if you want it sorted. Which opens up another whole can of worms such as what do you want to sort on, if you have a linked list of type Object there isn't really anything meaningful to sort on.

Categories