How to insert node at nth position in linked list - java

I am beginner in programming. I am trying to implement linked list in java i have tried to write function to insert element at nth position but its not working properly its not showing data before that position. It may seem silly question or mistake to you but as i am beginner so your answer will be helpful and it will be appreciated.
The Code is below.
class Node{
int data;
Node next;
Node(){
data=0;
next=null;
}
}
class LinkedList{
Node head;
LinkedList(){
head=null;
}
void pushB(int item){
Node temp=new Node();
temp.data=item;
temp.next=null;
if(head==null){
head=temp;
}
else{
temp.next=head;
head=temp;
}
}
void pushnth(int item, int pos){
Node cur=new Node();
cur.data=item;
cur.next=null;
Node temp=head;
int i=0;
while(i<pos-1){
temp=temp.next;
i++;
}
cur.next=temp;
head=cur;
}
void print(){
if(head==null){
System.out.println("List empty");
}
else{
Node temp=head;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
}
}
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
LinkedList l1=new LinkedList();
l1.pushB(90);
l1.pushB(80);
l1.pushB(70);
l1.pushB(60);
l1.pushB(50);
l1.pushB(30);
l1.pushB(20);
l1.pushB(10);
l1.pushnth(40,4);
l1.print();
}
}

Your pushnth method changes the head of the list, and therefore discards all the elements before the new element.
In order to add an element at the middle of the list you have to set 2 links.
The new node should point to the next link, which you do here :
cur.next=temp;
The node that comes before temp should be linked to the new node. That's the part you are missing.
Something like this should work :
void pushnth(int item, int pos){
Node cur=new Node();
cur.data=item;
Node temp=head;
int i=0;
while(i<pos-2){ // note that I changed the end condition
temp=temp.next;
i++;
}
// the new node is placed between temp and temp.next
cur.next = temp.next;
temp.next = cur;
}
Note that this code lacks some validations. For example, if there are too few elements in the linked list, this code will fail, so some additional checks should be added.

// please this is the correct add Node in position.
public static Node addAtPosition(Node head3, int position) {
// add node contains 0 in its data
Node nodeAddAtPosition = new Node(1000);
Node temp = head3;
if (position == 0) {
// add node contains 1000 in its data
nodeAddAtPosition.next = head3;// assigning addFront next to head
head3 = nodeAddAtPosition; // we need to return head assigning head to front.
} else {
for (int i = 1; i < position; i++) {
System.out.print(i);
temp = temp.next;
}
nodeAddAtPosition.next = temp.next;
temp.next = nodeAddAtPosition;
}
return head3;// return head
}

You must distinguish the case where the new item is inserted at the head of the list:
void pushnth(int item, int pos){
Node cur=new Node();
cur.data=item;
if (pos == 0) {
cur.next = head;
head = cur;
} else {
Node temp=head;
for (int i=1; i<pos; ++i) {
temp=temp.next;
}
cur.next = temp.next;
temp.next = cur;
}
}

Related

Not printing elements when value of n is equal to size of linked list

I am doing the program for removing nth element from end of the linked list. But problem is that when my size of lined list is equal to n then it is not returning head.next. Where I am doing wrong?
class Main{
static class Node {
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
}
Node head = null;
public void addFirst(int data) {
Node newnode = new Node(data);
if(head ==null){
head = newnode;
return;
}
newnode.next = head;
head = newnode;
}
//print list
public void PrintLL() {
Node n = head;
if(n.next==null){
System.out.println("NULL");
return;
}
while(n!=null){
System.out.print(n.data+ " --> ");
n= n.next;
}
}
//Find nth node from last
public Node RemoveNthNode(Node head,int nth){
if(head.next==null){
return null;
}
int size=0;
Node curNode=head;
while(curNode!=null){
curNode = curNode.next;
size++;
}
if(nth==size){
return head.next;
}
Node prevnode = head;
int i=1;
while(i<size-nth){
prevnode=prevnode.next;
i++;
}
prevnode.next = prevnode.next.next;
return head;
}
public static void main(String[] args) {
Main ll = new Main();
ll.addFirst(90);
ll.addFirst(40);
ll.addFirst(45);
System.out.println("\n");
ll.RemoveNthNode(ll.head, 3);
ll.PrintLL();
}
}
I tried the code that I have posted but it is not printing when n equal size of LL.
The reason is that although your function RemoveNthNode returns the head after the removal, the caller (in main) ignores the returned value, so that it never sees a change to head. The confusion may also be caused by the parameter that has the name head, which shadows the head property of the class instance.
As it is not intuitive that the caller needs to provide head as argument, while you would expect that the method would know what the head of the list is, I suggest to make it a void method which doesn't take the head argument.
You should also take care of the case where head is null.
Your PrintLL has a problem too: it doesn't print the node when the list has just one node.
Corrected code:
public void PrintLL() {
Node n = head;
while(n!=null){
System.out.print(n.data+ " --> ");
n= n.next;
}
System.out.println("NULL");
}
public void RemoveNthNode(int nth){
if(head == null || head.next==null){
head = null;
return;
}
int size=0;
Node curNode=head;
while(curNode!=null) {
curNode = curNode.next;
size++;
}
if(nth==size){
head = head.next;
return;
}
Node prevnode = head;
int i=1;
while(i<size-nth){
prevnode=prevnode.next;
i++;
}
prevnode.next = prevnode.next.next;
}
public static void main(String[] args) {
Main ll = new Main();
ll.addFirst(90);
ll.addFirst(40);
ll.addFirst(45);
ll.PrintLL();
ll.RemoveNthNode(3);
ll.PrintLL();
}

Recursive code for reversing a linked list is not working properly

Here tail is a pointer to the last element of linked list.
This code only works when there are odd numbers of nodes in a linked list and shows wrong output for even number of nodes. Please help what is the problem in the code and reason why it is happening?
public static class Node
{
int data;
Node next;
}
public static class LinkedList
{
Node head;
Node tail;
int size;
// many other member functions
private void reversePRHelper(Node node , Node prev)
{
if(node == null)
{
return;
}
Node Next = node.next;
node.next = prev;
prev = node;
reversePRHelper(Next , prev);
Node temp = this.head;
this.head = this.tail;
this.tail = temp;
}
public void reversePR()
{
reversePRHelper(head,null);
}
}
The bug in your code is that these three lines:
Node temp = this.head;
this.head = this.tail;
this.tail = temp;
should only be executed once, at the end, and not for each recursive call. So if you move those three statements out of your reversePrHelper method and into your reversePR method, your code will work.
private void reversePRHelper(Node node , Node prev)
{
if(node != null)
{
return;
}
Node Next = node.next;
node.next = prev;
prev = node;
reversePRHelper(Next , prev);
}
public void reversePR()
{
reversePRHelper(head,null);
Node temp = this.head;
this.head = this.tail;
this.tail = temp;
}
For me it is unclear however why you keep the tail as an attribute, since you can't navigate anywhere from the tail, as it has no next value. It would be different if your nodes would keep a reference to the previous element as well, but then it would be a double linked list.

Java Simple Linked List

I am taking a course in Data Structures at University and I am having troubles understanding why my Singly Linked List is not following FIFO algorithm.
Here is my Node/PSVM class:
public class Node {
protected int data;
protected Node next;
Node(int element){
this.data = element;
next = null;
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.addElement(300);
ll.addElement(600);
ll.addElement(900);
ll.addElement(1200);
ll.printList();
}
}
This is my Linked List Class:
public class LinkedList {
// create a reference of type node to point to head
Node head;
// keep track of the size of ll
int size = 0;
void printList() {
Node n = head;
for (int i = 0; i < llSize(); i++) {
System.out.print(n.data + " ");
n = n.next;
}
System.out.println("");
}
int llSize() {
return this.size;
}
boolean isEmpty() {
return size == 0;
}
void addElement(int element) {
if (isEmpty()) {
head = new Node(element);
} else {
Node nNode = new Node(element);
Node current = head;
while(current.next != null){
current = current.next;
}
current.next = nNode;
}
this.size++;
}
}
Sorry in advance if this is a basic question/problem. I have asked my professor and she sent me a YouTube link which really didn't help.
Thank you for your time.
The code has no bugs.
For the list to behave as FIFO, nodes will be added to one end and deleted from the opposite end.
Therefore, you will have to implement a delete operation. You can maintain separate reference to the head and tail node.

How to print a reverse linked list without using recursion in Java?

I try printing a reverse linked list without recursion and reversing the linked list. How can I do that?
Questions: How to print a reverse linked list without using recursion and not reversing the list?
Requirements: No extra space, cannot reverse a linked list, cannot use recursion.
Here is the definition of the linked list Node
class Node {
int value;
Node next;
public Node(int val) {
this.value = val;
}
}
Here is my recursion version of printReverseLinkedList:
public void printReverseList(Node head) {
Node temp = head;
if (temp.next != null) {
printReverseList(temp.next);
}
System.out.print(temp.value);
}
Performace does not matter, because I just want to do in this way.
If you may neither reverse the list, nor use recursion, the only way to do this is this:
public void printReversList(Node head) {
Node current = head; // used to search through the list
Node last = null; // stores the last element that we printed
while (last != head) { // = we didn't print everything yet
// find next element to print - it's one element before we reach "last"
while (current.next != last) {
current = current.next;
}
// Store the current element as the new last and print it
last = current;
system.out.print(last.value);
// reset current and start all over
current = head;
}
}
It is highly ineffective, but there is no other way I can think of.
How about using a Stack and then poping ? You said using another data-structure will be fine. This is not the fine code, but, should get the job done.
public void printReversList(Node head) {
Stack<Node> stack = new Stack<>();
while (head != null){
stack.push(head);
head = head.next;
}
while (!stack.isEmpty()){
System.out.println(stack.pop());
}
}
you can try this:
public void printReverseList(Node head) {
if(head == null) return;
Node prev = null;
Node revers = head;
Node nex = null;
while (revers != null){
nex = revers.next;
revers.next = prev;
prev = revers;
revers = nex;
}
System.out.println(prev);
}
void ReversePrint(Node head) {
// This is a "method-only" submission.
// You only need to complete this method.
Stack<Node> stk=new Stack<>();
Node temp=head;
while(temp!=null){
stk.push(temp);
temp=temp.next;
}
while(!stk.isEmpty()){
System.out.println(stk.pop().data);
}
}
public void printReverseList(Node head) {
Node node = head;
List<Integer> list = new ArrayList<Integer>();
if (head == null){
System.out.println(head.data);
}
else{
while (node != null){
list.add(0, node.data);
node = node.next;
}
for (int item:list){
System.out.println(item);
}
}
}

Linked List with Comparison

Hello I need to implement a Hashtable with a separate chaining. For that I am implementing a Node class and LinkedList. Nodes included in the linked list have the attributes data, count, a link to next and a link to previous.Linked list should not have values with duplicate value but given another node with the same value inserted, the count of that node should be increased. Above is my code but I could not figure out on how to implement the insert function so that when a duplicate node is found, the count is increased.
public void insertToHead(Node newNode) {
newNode.setNext(head);
head = newNode;
}
public void drop(Node newNode) {
newNode.getPrev().setNext(newNode.getNext());
}
public void insert(String newData) {
Node newNode = new Node(newData);
Node temp = head;
if (temp == null) {
insertToHead(newNode);
newNode.incrementCount();
nodeCount++;
} else {
for(int i=0;i<nodeCount;i++){
if(temp.getData().equals(newNode.getData())){
if(temp.getPrev()==null){
temp.incrementCount();
head=temp;
}
if(temp.getNext()==null){
temp.getPrev().setNext(null);
temp.incrementCount();
insertToHead(temp);
}
else{
temp.incrementCount();
drop(temp);
insertToHead(temp);
}
}
temp = temp.getNext();
}
insertToHead(newNode);
nodeCount++;
}
}
You need to traverse the linked list until you found an equal node and then increment the count on the same node, not the previous. If you reached the end of the list in that process, you do your normal insertion.
Node newNode = new Node(newData);
Node temp = head;
if (temp == null) {
insertToHead(newNode);
newNode.incrementCount();
nodeCount++;
} else {
while(temp != null){
if(temp.getData().equals(newNode.getData())){
temp.incrementCount();
break;
}
temp = temp.getNext();
}
// didn't find anything, prepend to the list
if(temp == null){
insertToHead(newNode);
nodeCount++;
}
}

Categories

Resources