Remove duplicates from an unsorted linked list - java
import java.util.*;
/*
* Remove duplicates from an unsorted linked list
*/
public class LinkedListNode {
public int data;
public LinkedListNode next;
public LinkedListNode(int data) {
this.data = data;
}
}
public class Task {
public static void deleteDups(LinkedListNode head){
Hashtable<Integer, Boolean> table=new Hashtable<Integer, Boolean>();
LinkedListNode previous=null;
//nth node is not null
while(head!=null){
//have duplicate
if(table.containsKey(head.data)){
//skip duplicate
previous.next=head.next;
}else{
//put the element into hashtable
table.put(head.data,true);
//move to the next element
previous=head;
}
//iterate
head=head.next;
}
}
public static void main (String args[]){
LinkedList<Integer> list=new LinkedList<Integer>();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(3);
list.addLast(3);
list.addLast(4);
list.addLast(4);
System.out.println(list);
LinkedListNode head=new LinkedListNode(list.getFirst());
Task.deleteDups(head);
System.out.println(list);
}
}
The result: [1, 2, 3, 3, 3, 4, 4]
[1, 2, 3, 3, 3, 4, 4]
It does not eliminate the duplicates.
Why doesn't the method work?
Iterate through the linked list,
adding each element to a hash table. When we discover a duplicate element, we remove the element and continue iterating. We can do this all in one pass since we are using a linked list.
The following solution takes O(n) time, n is the number of element in the linked list.
public static void deleteDups (LinkedListNode n){
Hashtable table = new Hashtable();
LinkedListNode previous = null;
while(n!=null){
if(table.containsKey(n.data)){
previous.next = n.next;
} else {
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
The solution you have provided does not modify the original list.
To modify the original list and remove duplicates, we can iterate with two pointers. Current: which iterates through LinkedList, and runner which checks all subsequent nodes for duplicates.
The code below runs in O(1) space but O(N square) time.
public void deleteDups(LinkedListNode head){
if(head == null)
return;
LinkedListNode currentNode = head;
while(currentNode!=null){
LinkedListNode runner = currentNode;
while(runner.next!=null){
if(runner.next.data == currentNode.data)
runner.next = runner.next.next;
else
runner = runner.next;
}
currentNode = currentNode.next;
}
}
Reference : Gayle laakmann mcdowell
Here's two ways of doing this in java. the method used above works in O(n) but requires additional space. Where as the second version runs in O(n^2) but requires no additional space.
import java.util.Hashtable;
public class LinkedList {
LinkedListNode head;
public static void main(String args[]){
LinkedList list = new LinkedList();
list.addNode(1);
list.addNode(1);
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.addNode(2);
list.print();
list.deleteDupsNoStorage(list.head);
System.out.println();
list.print();
}
public void print(){
LinkedListNode n = head;
while(n!=null){
System.out.print(n.data +" ");
n = n.next;
}
}
public void deleteDups(LinkedListNode n){
Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
LinkedListNode prev = null;
while(n !=null){
if(table.containsKey(new Integer(n.data))){
prev.next = n.next; //skip the previously stored references next node
}else{
table.put(new Integer(n.data) , true);
prev = n; //stores a reference to n
}
n = n.next;
}
}
public void deleteDupsNoStorage(LinkedListNode n){
LinkedListNode current = n;
while(current!=null){
LinkedListNode runner = current;
while(runner.next!=null){
if(runner.next.data == current.data){
runner.next = runner.next.next;
}else{
runner = runner.next;
}
}
current = current.next;
}
}
public void addNode(int d){
LinkedListNode n = new LinkedListNode(d);
if(this.head==null){
this.head = n;
}else{
n.next = head;
head = n;
}
}
private class LinkedListNode{
LinkedListNode next;
int data;
public LinkedListNode(int d){
this.data = d;
}
}
}
You can use the following java method to remove duplicates:
1) With complexity of O(n^2)
public void removeDuplicate(Node head) {
Node temp = head;
Node duplicate = null; //will point to duplicate node
Node prev = null; //prev node to duplicate node
while (temp != null) { //iterate through all nodes
Node curr = temp;
while (curr != null) { //compare each one by one
/*in case of duplicate skip the node by using prev node*/
if (curr.getData() == temp.getData() && temp != curr) {
duplicate = curr;
prev.setNext(duplicate.getNext());
}
prev = curr;
curr = curr.getNext();
}
temp = temp.getNext();
}
}
Input:1=>2=>3=>5=>5=>1=>3=>
Output:1=>2=>3=>5=>
2)With complexity of O(n) using hash table.
public void removeDuplicateUsingMap(Node head) {
Node temp = head;
Map<Integer, Boolean> hash_map = new HashMap<Integer, Boolean>(); //create a hash map
while (temp != null) {
if (hash_map.get(temp.getData()) == null) { //if key is not set then set is false
hash_map.put(temp.getData(), false);
} else { //if key is already there,then delete the node
deleteNode(temp,head);
}
temp = temp.getNext();
}
}
public void deleteNode(Node n, Node start) {
Node temp = start;
if (n == start) {
start = null;
} else {
while (temp.getNext() != n) {
temp = temp.getNext();
}
temp.setNext(n.getNext());
}
}
Input:1=>2=>3=>5=>5=>1=>3=>
Output:1=>2=>3=>5=>
Ans is in C . first sorted link list sort() in nlog time and then deleted duplicate del_dip() .
node * partition(node *start)
{
node *l1=start;
node *temp1=NULL;
node *temp2=NULL;
if(start->next==NULL)
return start;
node * l2=f_b_split(start);
if(l1->next!=NULL)
temp1=partition(l1);
if(l2->next!=NULL)
temp2=partition(l2);
if(temp1==NULL || temp2==NULL)
{
if(temp1==NULL && temp2==NULL)
temp1=s_m(l1,l2);
else if(temp1==NULL)
temp1=s_m(l1,temp2);
else if(temp2==NULL)
temp1=s_m(temp1,l2);
}
else
temp1=s_m(temp1,temp2);
return temp1;
}
node * sort(node * start)
{
node * temp=partition(start);
return temp;
}
void del_dup(node * start)
{
node * temp;
start=sort(start);
while(start!=NULL)
{
if(start->next!=NULL && start->data==start->next->data )
{
temp=start->next;
start->next=start->next->next;
free(temp);
continue;
}
start=start->next;
}
}
void main()
{
del_dup(list1);
print(list1);
}
Try this it is working for delete the duplicate elements from your linkedList
package com.loknath.lab;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class Task {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(3);
list.addLast(3);
list.addLast(4);
list.addLast(4);
deleteDups(list);
System.out.println(list);
}
public static void deleteDups(LinkedList<Integer> list) {
Set s = new HashSet<Integer>();
s.addAll(list);
list.clear();
list.addAll(s);
}
}
I think you can just use one iterator current to finish this problem
public void compress(){
ListNode current = front;
HashSet<Integer> set = new HashSet<Integer>();
set.add(current.data);
while(current.next != null){
if(set.contains(current.next.data)){
current.next = current.next.next; }
else{
set.add(current.next.data);
current = current.next;
}
}
}
Here is a very easy version.
LinkedList<Integer> a = new LinkedList<Integer>(){{
add(1);
add(1);
}}
Set<Integer> set = new HashSet<Integer>(a);
a = new LinkedList<Integer>(set);
Very concise. Isn't it?
The first problem is that
LinkedListNode head=new LinkedListNode(list.getFirst());
does not actually initialize head with the contents of list. list.getFirst() simply returns the Integer 1, and head contains 1 as its only element. You would have to initialize head by looping through list in order to get all of the elements.
In addition, although
Task.deleteDups(head)
modifies head, this leaves list completely unchanged—there is no reason why the changes to head should propagate to list. Therefore, to check your method, you would have to loop down head and print out each element, rather than printing out list again.
Try This.Its working.
// Removing Duplicates in Linked List
import java.io.*;
import java.util.*;
import java.text.*;
class LinkedListNode{
int data;
LinkedListNode next=null;
public LinkedListNode(int d){
data=d;
}
void appendToTail(int d){
LinkedListNode newnode = new LinkedListNode(d);
LinkedListNode n=this;
while(n.next!=null){
n=n.next;
}
n.next=newnode;
}
void print(){
LinkedListNode n=this;
System.out.print("Linked List: ");
while(n.next!=null){
System.out.print(n.data+" -> ");
n=n.next;
}
System.out.println(n.data);
}
}
class LinkedList2_0
{
public static void deletenode2(LinkedListNode head,int d){
LinkedListNode n=head;
// If It's head node
if(n.data==d){
head=n.next;
}
//If its other
while(n.next!=null){
if(n.next.data==d){
n.next=n.next.next;
}
n=n.next;
}
}
public static void removeDuplicateWithBuffer(LinkedListNode head){
LinkedListNode n=head;
LinkedListNode prev=null;
Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
while(n!=null){
if(table.containsKey(n.data)){
prev.next=n.next;
}
else{
table.put(n.data,true);
prev=n;
}
n=n.next;
}
}
public static void removeDuplicateWithoutBuffer(LinkedListNode head){
LinkedListNode currentNode=head;
while(currentNode!=null){
LinkedListNode runner=currentNode;
while(runner.next!=null){
if(runner.next.data==currentNode.data){
runner.next=runner.next.next;
}
else
runner=runner.next;
}
currentNode=currentNode.next;
}
}
public static void main(String[] args) throws java.lang.Exception {
LinkedListNode head=new LinkedListNode(1);
head.appendToTail(1);
head.appendToTail(3);
head.appendToTail(2);
head.appendToTail(3);
head.appendToTail(4);
head.appendToTail(5);
head.print();
System.out.print("After Delete: ");
deletenode2(head,4);
head.print();
//System.out.print("After Removing Duplicates(with buffer): ");
//removeDuplicateWithBuffer(head);
//head.print();
System.out.print("After Removing Duplicates(Without buffer): ");
removeDuplicateWithoutBuffer(head);
head.print();
}
}
here are a couple other solutions (slightly different from Cracking coding inerview, easier to read IMO).
public void deleteDupes(Node head) {
Node current = head;
while (current != null) {
Node next = current.next;
while (next != null) {
if (current.data == next.data) {
current.next = next.next;
break;
}
next = next.next;
}
current = current.next;
}
}
public void deleteDupes(Node head) {
Node current = head;
while (current != null) {
Node next = current.next;
while (next != null) {
if (current.data == next.data) {
current.next = next.next;
current = current.next;
next = current.next;
} else {
next = next.next;
}
}
current = current.next;
}
}
It's simple way without HashSet or creation Node.
public String removeDuplicates(String str) {
LinkedList<Character> chars = new LinkedList<Character>();
for(Character c: str.toCharArray()){
chars.add(c);
}
for (int i = 0; i < chars.size(); i++){
for (int j = i+1; j < chars.size(); j++){
if(chars.get(j) == chars.get(i)){
chars.remove(j);
j--;
}
}
}
return new String(chars.toString());
}
And to verify it:
#Test
public void verifyThatNoDuplicatesInLinkedList(){
CodeDataStructures dataStructures = new CodeDataStructures();
assertEquals("abcdefghjk", dataStructures.removeDuplicates("abcdefgabcdeaaaaaaaaafabcdeabcdefgabcdbbbbbbefabcdefghjkabcdefghjkghjkhjkabcdefghabcdefghjkjfghjkabcdefghjkghjkhjkabcdefghabcdefghjkj")
.replace(",", "")
.replace("]", "")
.replace("[", "")
.replace(" ", ""));
}
LinkedList<Node> list = new LinkedList<Node>();
for(int i=0; i<list.size(); i++){
for(int j=0; j<list.size(); j++){
if(list.get(i).data == list.get(j).data && i!=j){
if(i<j){
list.remove(j);
if(list.get(j)!= null){
list.get(j-1).next = list.get(j);
}else{
list.get(j-1).next = null;
}
}
else{
if(i>j){
list.remove(i);
if(list.get(i) != null){
list.get(j).next = list.get(i);
}else{
list.get(j).next = null;
}
}
}
}
}
}
/**
*
* Remove duplicates from an unsorted linked list.
*/
public class RemoveDuplicates {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("Apple");
list.add("Grape");
list.add("Apple");
HashSet<String> set = removeDuplicatesFromList(list);
System.out.println("Removed duplicates" + set);
}
public static HashSet<String> removeDuplicatesFromList(LinkedList<String> list){
HashSet<String> set = new LinkedHashSet<String>();
set.addAll(list);
return set;
}
}
Below code implements this without needing any temporary buffer. It starts with comparing first and second nodes, if not a match, it adds char at first node to second node then proceeds comparing all chars in second node to char at third node and so on. After comperison is complete, before leaving the node it clears everything that is added and restores its old value which resides at node.val.char(0)
F > FO > FOL > (match found, node.next = node.next.next) > (again match, discard it) > FOLW > ....
public void onlyUnique(){
Node node = first;
while(node.next != null){
for(int i = 0 ; i < node.val.length(); i++){
if(node.val.charAt(i) == node.next.val.charAt(0)){
node.next = node.next.next;
}else{
if(node.next.next != null){ //no need to copy everything to the last element
node.next.val = node.next.val + node.val;
}
node.val = node.val.charAt(0)+ "";
}
}
node = node.next;
}
}
All the solutions given above looks optimised but most of them defines custom Node as a part of solution. Here is a simple and practical solution using Java's LinkedList and HashSet which does not confine to use the preexisting libraries and methods.
Time Complexity : O(n)
Space Complexity: O(n)
#SuppressWarnings({ "unchecked", "rawtypes" })
private static LinkedList<?> removeDupsUsingHashSet(LinkedList<?> list) {
HashSet set = new HashSet<>();
for (int i = 0; i < list.size();) {
if (set.contains(list.get(i))) {
list.remove(i);
continue;
} else {
set.add(list.get(i));
i++;
}
}
return list;
}
This also preserves the list order.
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);
linkedList.add(6);
deleteElement(linkedList);
System.out.println(linkedList);
}
private static void deleteElement(LinkedList<Integer> linkedList) {
Set s = new HashSet<Integer>();
s.addAll(linkedList);
linkedList.clear();
linkedList.addAll(s);
}
This is my Java version
// Remove duplicate from a sorted linked list
public void removeDuplicates() {
Node current = head;
Node next = null;
/* Traverse list till the last node */
while (current != null) {
next = current;
/*
* Compare current node with the next node and keep on deleting them until it
* matches the current node data
*/
while (next != null && current.getValue() == next.getValue()) {
next = next.getNext();
}
/*
* Set current node next to the next different element denoted by temp
*/
current.setNext(next);
current = current.getNext();
}
}
1.Fully Dynamic Approach
2.Remove Duplicates from LinkedList
3.LinkedList Dynamic Object based creation
Thank you
import java.util.Scanner;
class Node{
int data;
Node next;
public Node(int data)
{
this.data=data;
this.next=null;
}
}
class Solution
{
public static Node insert(Node head,int data)
{
Node p=new Node(data);
if(head==null)
{
head=p;
}
else if(head.next==null)
{
head.next=p;
}
else
{
Node start=head;
while(start.next!=null)
{
start=start.next;
}
start.next=p;
return head;
//System.out.println();
}
return head;
}
public static void display(Node head)
{
Node start=head;
while(start!=null)
{
System.out.print(start.data+" ");
start=start.next;
}
}
public static Node remove_duplicates(Node head)
{
if(head==null||head.next==null)
{
return head;
}
Node prev=head;
Node p=head.next;
while(p!=null)
{
if(p.data==prev.data)
{
prev.next=p.next;
p=p.next;
}
else{
prev=p;
p=p.next;
}
}
return head;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Node head=null;
int T=sc.nextInt();
while(T-->0)
{
int ele=sc.nextInt();
head=insert(head,ele);
}
head=remove_duplicates(head);
display(head);
}
}
input:
5
1 1 2 3 3
output:
1 2 3
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(); }
Determine the Object (book) that appears first alphabetically
I was tasked with creating my own linked list class, using a book class i made. One of the questions was to Determine the book that appears first alphabetically. i was able to sort the Linked list alphabetically using bubble sort(i know its not efficient but im still new) here is the code. public void alphaBubbleSort() { int size = size(); if (size > 1) { boolean wasChanged; do { Node current = head; Node previous = null; Node next = head.next; wasChanged = false; while (next != null) { if (current.book.getName().compareToIgnoreCase(next.book.getName()) > 0) { wasChanged = true; if (previous != null) { Node sig = next.next; previous.next = next; next.next = current; current.next = sig; } else { Node temp = next.next; head = next; next.next = current; current.next = temp; } previous = next; next = current.next; } else { previous = current; current = next; next = next.next; } } } while (wasChanged); } } my problem is i only want the front node and i do not want to alter the linked list order. i tried to do this in my main. Linky tempLinky = new Linky(); // create temp linked list tempLinky = linky; // copy temp main linked list to temp tempLinky.alphaBubbleSort(); // sort temp list System.out.println(tempLinky.peek());// return object in first node This did not seem to work. Ive tried some other code that does not work, so ive come here as a last resort.
If you need to find the first book alphabetically, there's no need to sort the entire list (and, as you commented, you don't want to alter the list's order anyway). Instead, you could iterate over the list and keep the "first" object as you go: public Book getFirstAlphabetically() { Node current = head; Book retVal = head.book; while (current != null) { if (current.book.getName().compareToIgnoreCase(retVal.getName()) < 0) { retVal = current.book; } current = current.next; } return retVal; }
Here's an example: import java.util.Random; class Book { String title; Book(String title){this.title = title;} } class Node { Book b; Node next; Node(Book b){this.b = b;} } public class Main { static Book least(Node head){ if (head == null) return null; Book least = head.b; for(Node n=head.next; n.next!=null; n=n.next) least = least.title.compareTo(n.b.title) > 0 ? n.b : least; return least; } static void print(Node head){ for(Node n=head; n.next!=null; n=n.next) System.out.println(n.b.title); } static String randString(){ Random r = new Random(); int len = r.nextInt(20)+1; char[] chars = new char[len]; for(int i=0; i<chars.length; i++) chars[i]= (char) (r.nextInt(26)+97); return new String(chars); } public static void main(String[] args) { Node head = new Node(new Book(randString())); Node next = head; for(int i = 0; i<20; i++) next = next.next = new Node(new Book(randString())); print(head); System.out.println("=========="); System.out.println(least(head).title); } }
how to form and traverse an array of linked list in java?
I have written a single linked list for insertion of elements, where each element is having two data values. Now what I want is that to make like jagged array. That means I want a 1d array and where each element will be a linkedlist of items. Is it really possible to make the below single linkedlist into an array of linkedlist, i.e. L[0],L[1], etc. each will be the starting of similar linkedlist. Then what shall I modify in the code given below so that I can form and traverse and get the values printed. // Java Program to insert in a sorted list class LinkedList1 { Node head; // head of list /* Linked list Node*/ class Node { int s; int a; Node next; Node(int starting_time,int arrival_time) {s = starting_time; a=arrival_time;next = null; } } /* function to insert a new_node in a list. */ void sortedInsert(Node new_node) { Node current; /* Special case for head node */ if (head == null || head.a >= new_node.a) { new_node.next = head; head = new_node; } else { /* Locate the node before point of insertion. */ current = head; while (current.next != null && current.next.a < new_node.a) current = current.next; new_node.next = current.next; current.next = new_node; } } /*Utility functions*/ /* Function to create a node */ Node newNode(int s,int a) { Node x = new Node(s,a); return x; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print("["+temp.s+","+temp.a+"] "); temp = temp.next; } } /* Drier function to test above methods */ public static void main(String args[]) { LinkedList1 llist = new LinkedList1(); Node new_node; new_node = llist.newNode(5,6); llist.sortedInsert(new_node); new_node = llist.newNode(10,2); llist.sortedInsert(new_node); new_node = llist.newNode(7,3); llist.sortedInsert(new_node); new_node = llist.newNode(3,4); llist.sortedInsert(new_node); new_node = llist.newNode(1,5); llist.sortedInsert(new_node); new_node = llist.newNode(9,1); llist.sortedInsert(new_node); System.out.println("Created Linked List"); llist.printList(); } }
I have wrapped up the LinkedList1 class inside LinkedListArray and create couple of constructors and a get and insert method. Similarly, you can write other methods as required. Hope this will make things clear. public class LinkedListArray{ private int DEFAULT_CAPACITY=10; private int SIZE=0; private LinkedList1[] arr; public LinkedListArray() { arr=new LinkedList1[DEFAULT_CAPACITY]; } public LinkedListArray(int capacity) { arr=new LinkedList1[capacity]; } public LinkedList1 insert(int index, LinkedListArray.LinkedList1.Node Node) { if(arr[index]==null) arr[index]=new LinkedList1(); arr[index].sortedInsert(Node);; SIZE++; return arr[index]; } public LinkedList1 get(int index) { return arr[index]; } public int size() { return SIZE; } //Java Program to insert in a sorted list class LinkedList1 { public LinkedList1() {} Node head; // head of list /* Linked list Node*/ class Node { int s; int a; Node next; Node(int starting_time,int arrival_time) {s = starting_time; a=arrival_time;next = null; } } /* function to insert a new_node in a list. */ void sortedInsert(Node new_node) { Node current; /* Special case for head node */ if (head == null || head.a >= new_node.a) { new_node.next = head; head = new_node; } else { /* Locate the node before point of insertion. */ current = head; while (current.next != null && current.next.a < new_node.a) current = current.next; new_node.next = current.next; current.next = new_node; } } /*Utility functions*/ /* Function to create a node */ Node newNode(int s,int a) { Node x = new Node(s,a); return x; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print("["+temp.s+","+temp.a+"] "); temp = temp.next; } } /* Drier function to test above methods */ } public static void main(String args[]) { LinkedListArray arr=new LinkedListArray(); arr.insert(0, new LinkedListArray().new LinkedList1().newNode(5, 4)); arr.insert(0, new LinkedListArray().new LinkedList1().newNode(10, 4)); arr.insert(0, new LinkedListArray().new LinkedList1().newNode(4, 34)); System.out.println("Created Linked List and inserted in array"); arr.get(0).printList(); } }
Reverse Singly Linked List Java [duplicate]
This question already has answers here: How to reverse a singly-linked list in blocks of some given size in O(n) time in place? (4 answers) Closed 4 years ago. Can someone tell me why my code dosent work? I want to reverse a single linked list in java: This is the method (that doesnt work correctly) public void reverseList(){ Node before = null; Node tmp = head; Node next = tmp.next; while(tmp != null){ if(next == null) return; tmp.next = before; before = tmp; tmp = next; next = next.next; } } And this is the Node class: public class Node{ public int data; public Node next; public Node(int data, Node next){ this.data = data; this.next = next; } } On input 4->3->2->1 I got output 4. I debugged it and it sets pointers correctly but still I dont get why it outputs only 4.
Node next = tmp.next; while(tmp != null){ So what happens when tmp == null? You almost got it, though. Node before = null; Node tmp = head; while (tmp != null) { Node next = tmp.next; tmp.next = before; before = tmp; tmp = next; } head = before; Or in nicer (?) naming: Node reversedPart = null; Node current = head; while (current != null) { Node next = current.next; current.next = reversedPart; reversedPart = current; current = next; } head = reversedPart; ASCII art: <__<__<__ __ : reversedPart : head (__)__ __ __ head : current: > > >
public Node<E> reverseList(Node<E> node) { if (node == null || node.next == null) { return node; } Node<E> currentNode = node; Node<E> previousNode = null; Node<E> nextNode = null; while (currentNode != null) { nextNode = currentNode.next; currentNode.next = previousNode; previousNode = currentNode; currentNode = nextNode; } return previousNode; }
The method for reversing a linked list is as below; Reverse Method public void reverseList() { Node<E> curr = head; Node<E> pre = null; Node<E> incoming = null; while(curr != null) { incoming = curr.next; // store incoming item curr.next = pre; // swap nodes pre = curr; // increment also pre curr = incoming; // increment current } head = pre; // pre is the latest item where // curr is null } Three references are needed to reverse a list: pre, curr, incoming ... pre curr incoming ... --> (n-1) --> (n) --> (n+1) --> ... To reverse a node, you have to store previous element, so that you can use the simple stament; curr.next = pre; To reverse the current element's direction. However, to iterate over the list, you have to store incoming element before the execution of the statement above because as reversing the current element's next reference, you don't know the incoming element anymore, that's why a third reference needed. The demo code is as below; LinkedList Sample Class public class LinkedList<E> { protected Node<E> head; public LinkedList() { head = null; } public LinkedList(E[] list) { this(); addAll(list); } public void addAll(E[] list) { for(int i = 0; i < list.length; i++) add(list[i]); } public void add(E e) { if(head == null) head = new Node<E>(e); else { Node<E> temp = head; while(temp.next != null) temp = temp.next; temp.next = new Node<E>(e); } } public void reverseList() { Node<E> curr = head; Node<E> pre = null; Node<E> incoming = null; while(curr != null) { incoming = curr.next; // store incoming item curr.next = pre; // swap nodes pre = curr; // increment also pre curr = incoming; // increment current } head = pre; // pre is the latest item where // curr is null } public void printList() { Node<E> temp = head; System.out.print("List: "); while(temp != null) { System.out.print(temp + " "); temp = temp.next; } System.out.println(); } public static class Node<E> { protected E e; protected Node<E> next; public Node(E e) { this.e = e; this.next = null; } #Override public String toString() { return e.toString(); } } } Test Code public class ReverseLinkedList { public static void main(String[] args) { Integer[] list = { 4, 3, 2, 1 }; LinkedList<Integer> linkedList = new LinkedList<Integer>(list); linkedList.printList(); linkedList.reverseList(); linkedList.printList(); } } Output List: 4 3 2 1 List: 1 2 3 4
If this isn't homework and you are doing this "manually" on purpose, then I would recommend using Collections.reverse(list); Collections.reverse() returns void, and your list is reversed after the call.
We can have three nodes previous,current and next. public void reverseLinkedlist() { /* * Have three nodes i.e previousNode,currentNode and nextNode When currentNode is starting node, then previousNode will be null Assign currentNode.next to previousNode to reverse the link. In each iteration move currentNode and previousNode by 1 node. */ Node previousNode = null; Node currentNode = head; while (currentNode != null) { Node nextNode = currentNode.next; currentNode.next = previousNode; previousNode = currentNode; currentNode = nextNode; } head = previousNode; }
public void reverse() { Node prev = null; Node current = head; Node next = current.next; while(current.next != null) { current.next = prev; prev = current; current = next; next = current.next; } current.next = prev; head = current; }
// Java program for reversing the linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } // Function to reverse the linked list Node reverse(Node node) { Node prev = null; Node current = node; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(85); list.head.next = new Node(15); list.head.next.next = new Node(4); list.head.next.next.next = new Node(20); System.out.println("Given Linked list"); list.printList(head); head = list.reverse(head); System.out.println(""); System.out.println("Reversed linked list "); list.printList(head); } } OUTPUT: - Given Linked list 85 15 4 20 Reversed linked list 20 4 15 85
I know the recursive solution is not the optimal one, but just wanted to add one here: public class LinkedListDemo { static class Node { int val; Node next; public Node(int val, Node next) { this.val = val; this.next = next; } #Override public String toString() { return "" + val; } } public static void main(String[] args) { Node n = new Node(1, new Node(2, new Node(3, new Node(20, null)))); display(n); n = reverse(n); display(n); } static Node reverse(Node n) { Node tail = n; while (tail.next != null) { tail = tail.next; } reverseHelper(n); return (tail); } static Node reverseHelper(Node n) { if (n.next != null) { Node reverse = reverseHelper(n.next); reverse.next = n; n.next = null; return (n); } return (n); } static void display(Node n) { for (; n != null; n = n.next) { System.out.println(n); } } }
I don't get it... why not doing this : private LinkedList reverseLinkedList(LinkedList originalList){ LinkedList reversedList = new LinkedList<>(); for(int i=0 ; i<originalList.size() ; i++){ reversedList.add(0, originalList.get(i)); } return reversedList; } I find this easier.
A more elegant solution would be to use recursion void ReverseList(ListNode current, ListNode previous) { if(current.Next != null) { ReverseList(current.Next, current); ListNode temp = current.Next; temp.Next = current; current.Next = previous; } }
I tried the below code and it works fine: Node head = firstNode; Node current = head; while(current != null && current.next != null){ Node temp = current.next; current.next = temp.next; temp.next = head; head = temp; } Basically one by one it sets the next pointer of one node to its next to next node, so from next onwards all nodes are attached at the back of the list.
Node reverse_rec(Node start) { if (start == null || start -> next == null) { return start; } Node new_start = reverse(start->next); start->next->next = start; start->next = null; return new_start; } Node reverse(Node start) { Node cur = start; Node bef = null; while (cur != null) { Node nex = cur.next; cur.next = bef; bef = cur; cur = nex; } return bef; }
I think your problem is that your initially last element next attribute isn't being changed becuase of your condition if(next == null) return; Is at the beginning of your loop. I would move it right after tmp.next has been assigned: while(tmp != null){ tmp.next = before; if(next == null) return; before = tmp; tmp = next; next = next.next; }
Use this. if (current== null || current.next==null) return current; Node nextItem = current.next; current.next = null; Node reverseRest = reverse(nextItem); nextItem.next = current; return reverseRest or Java Program to reverse a Singly Linked List
package com.three; public class Link { int a; Link Next; public Link(int i){ a=i; } } public class LinkList { Link First = null; public void insertFirst(int a){ Link objLink = new Link(a); objLink.Next=First; First = objLink; } public void displayLink(){ Link current = First; while(current!=null){ System.out.println(current.a); current = current.Next; } } public void ReverseLink(){ Link current = First; Link Previous = null; Link temp = null; while(current!=null){ if(current==First) temp = current.Next; else temp=current.Next; if(temp==null){ First = current; //return; } current.Next=Previous; Previous=current; //System.out.println(Previous); current = temp; } } public static void main(String args[]){ LinkList objLinkList = new LinkList(); objLinkList.insertFirst(1); objLinkList.insertFirst(2); objLinkList.insertFirst(3); objLinkList.insertFirst(4); objLinkList.insertFirst(5); objLinkList.insertFirst(6); objLinkList.insertFirst(7); objLinkList.insertFirst(8); objLinkList.displayLink(); System.out.println("-----------------------------"); objLinkList.ReverseLink(); objLinkList.displayLink(); } }
You can also try this LinkedListNode pointer = head; LinkedListNode prev = null, curr = null; /* Pointer variable loops through the LL */ while(pointer != null) { /* Proceed the pointer variable. Before that, store the current pointer. */ curr = pointer; // pointer = pointer.next; /* Reverse the link */ curr.next = prev; /* Current becomes previous for the next iteration */ prev = curr; } System.out.println(prev.printForward());
package LinkedList; import java.util.LinkedList; public class LinkedListNode { private int value; private LinkedListNode next = null; public LinkedListNode(int i) { this.value = i; } public LinkedListNode addNode(int i) { this.next = new LinkedListNode(i); return next; } public LinkedListNode getNext() { return next; } #Override public String toString() { String restElement = value+"->"; LinkedListNode newNext = getNext(); while(newNext != null) {restElement = restElement + newNext.value + "->"; newNext = newNext.getNext();} restElement = restElement +newNext; return restElement; } public static void main(String[] args) { LinkedListNode headnode = new LinkedListNode(1); headnode.addNode(2).addNode(3).addNode(4).addNode(5).addNode(6); System.out.println(headnode); headnode = reverse(null,headnode,headnode.getNext()); System.out.println(headnode); } private static LinkedListNode reverse(LinkedListNode prev, LinkedListNode current, LinkedListNode next) { current.setNext(prev); if(next == null) return current; return reverse(current,next,next.getNext()); } private void setNext(LinkedListNode prev) { this.next = prev; } }
public class ReverseLinkedList { public static void main(String args[]){ LinkedList<String> linkedList = new LinkedList<String>(); linkedList.add("a"); linkedList.add("b"); linkedList.add("c"); linkedList.add("d"); linkedList.add("e"); linkedList.add("f"); System.out.println("Original linkedList:"); for(int i = 0; i <=linkedList.size()-1; i++){ System.out.println(" - "+ linkedList.get(i)); } LinkedList<String> reversedlinkedList = reverse(linkedList); System.out.println("Reversed linkedList:"); for(int i = 0; i <=reversedlinkedList.size()-1; i++){ System.out.println(" - "+ reversedlinkedList.get(i)); } } public static LinkedList<String> reverse(LinkedList<String> linkedList){ for(int i = 0; i < linkedList.size()/2; i++){ String temp = linkedList.get(i); linkedList.set(i, linkedList.get(linkedList.size()-1-i)); linkedList.set((linkedList.size()-1-i), temp); } return linkedList; } }
To reverse a singly linked list you should have three nodes, top, beforeTop and AfterTop. Top is the header of singly linked list, hence beforeTop would be null and afterTop would be next element of top and with each iteration move forward beforeTop is assigned top and top is assigned afterTop(i.e. top.next). private static Node inverse(Node top) { Node beforeTop=null, afterTop; while(top!=null){ afterTop=top.next; top.next=beforeTop; beforeTop=top; top=afterTop; } return beforeTop; }
Using Recursion It's too easy : package com.config; import java.util.Scanner; public class Help { public static void main(String args[]){ Scanner sc = new Scanner(System.in); Node head = null; Node temp = null; int choice = 0; boolean flage = true; do{ Node node = new Node(); System.out.println("Enter Node"); node.data = sc.nextInt(); if(flage){ head = node; flage = false; } if(temp!=null) temp.next = node; temp = node; System.out.println("Enter 0 to exit."); choice = sc.nextInt(); }while(choice!=0); Help.getAll(head); Node reverse = Help.reverse(head,null); //reverse = Help.reverse(head, null); Help.getAll(reverse); } public static void getAll(Node head){ if(head==null) return ; System.out.println(head.data+"Memory Add "+head.hashCode()); getAll(head.next); } public static Node reverse(Node head,Node tail){ Node next = head.next; head.next = tail; return (next!=null? reverse(next,head) : head); } } class Node{ int data = 0; Node next = null; }
Node Reverse(Node head) { Node n,rev; rev = new Node(); rev.data = head.data; rev.next = null; while(head.next != null){ n = new Node(); head = head.next; n.data = head.data; n.next = rev; rev = n; n=null; } return rev; } Use above function to reverse single linked list.
public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } check more details about complexity analysis http://javamicro.com/ref-card/DS-Algo/How-to-Reverse-Singly-Linked-List?
public static LinkedList reverseLinkedList(LinkedList node) { if (node == null || node.getNext() == null) { return node; } LinkedList remaining = reverseLinkedList(node.getNext()); node.getNext().setNext(node); node.setNext(null); return remaining; }
/** * Reverse LinkedList * #author asharda * */ class Node { int data; Node next; Node(int data) { this.data=data; } } public class ReverseLinkedList { static Node root; Node temp=null; public void insert(int data) { if(root==null) { root=new Node(data); } else { temp=root; while(temp.next!=null) { temp=temp.next; } Node newNode=new Node(data); temp.next=newNode; } }//end of insert public void display(Node head) { while(head!=null) { System.out.println(head.data); head=head.next; } } public Node reverseLinkedList(Node head) { Node newNode; Node tempr=null; while(head!=null) { newNode=new Node(head.data); newNode.next=tempr; tempr=newNode; head=head.next; } return tempr; } public static void main(String[] args) { ReverseLinkedList r=new ReverseLinkedList(); r.insert(10); r.insert(20); r.insert(30); r.display(root); Node t=r.reverseLinkedList(root); r.display(t); } }
public class SinglyLinkedListImpl<T> { private Node<T> head; public void add(T element) { Node<T> item = new Node<T>(element); if (head == null) { head = item; } else { Node<T> temp = head; while (temp.next != null) { temp = temp.next; } temp.next = item; } } private void reverse() { Node<T> temp = null; Node<T> next = null; while (head != null) { next = head.next; head.next = temp; temp = head; head = next; } head = temp; } void printList(Node<T> node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } System.out.println(); } public static void main(String a[]) { SinglyLinkedListImpl<Integer> sl = new SinglyLinkedListImpl<Integer>(); sl.add(1); sl.add(2); sl.add(3); sl.add(4); sl.printList(sl.head); sl.reverse(); sl.printList(sl.head); } static class Node<T> { private T data; private Node<T> next; public Node(T data) { super(); this.data = data; } } }
public class Linkedtest { public static void reverse(List<Object> list) { int lenght = list.size(); for (int i = 0; i < lenght / 2; i++) { Object as = list.get(i); list.set(i, list.get(lenght - 1 - i)); list.set(lenght - 1 - i, as); } } public static void main(String[] args) { LinkedList<Object> st = new LinkedList<Object>(); st.add(1); st.add(2); st.add(3); st.add(4); st.add(5); Linkedtest.reverse(st); System.out.println("Reverse Value will be:"+st); } } This will be useful for any type of collection Object.
Delete k-th element in a linked list (Java implementation)
I am trying this program but i am not able to achieve deletion. The execution is going into infinite loop. Also, i am not sure if i am forming linked list properly. What am i missing in the following program: public class SpecificNodeRemoval { private static class Node { String item; Node next; Node prev; private Node(String item, Node next, Node prev) { this.item = item; this.next = next; this.prev = prev; } } public static void main(String[] args) { int k = 3; Node fourth = new Node("Fourth", null, null); Node third = new Node("Third", fourth, null); Node second = new Node("Second", third, null); Node first = new Node("First", second, null); second.prev = first; third.prev = second; fourth.prev = third; Node list = first; Node result = removalKthNode(list, k); int j = 1; while(result.next!=null){ System.out.println(j+": "+result.item); } } private static Node removalKthNode(Node first, int k) { Node temp = first; for(int i=1; i < k; i++) { temp = temp.next; } temp.prev.next = temp.next; temp.next.prev = temp.prev; return temp; } } THANKS A TON for answer and comments.. the working program is listed below: public class SpecificNodeRemoval { private static class Node { String item; Node next; Node prev; private Node(String item, Node next, Node prev) { this.item = item; this.next = next; this.prev = prev; } } public static void main(String[] args) { int k = 3; Node fourth = new Node("Fourth", null, null); Node third = new Node("Third", fourth, null); Node second = new Node("Second", third, null); Node first = new Node("First", second, null); second.prev = first; third.prev = second; fourth.prev = third; Node list = first; Node result = removalKthNode(list, k); int j = 1; while(result != null){ System.out.println(j+": "+result.item); result = result.next; j++; } } private static Node removalKthNode(Node first, int k) { Node temp = first; for(int i=1; i < k; i++) { temp = temp.next; } temp.prev.next = temp.next; temp.next.prev = temp.prev; return first; } } The output is: 1: First 2: Second 3: Fourth
This looks like the culprit. while(result.next!=null){ System.out.println(j+": "+result.item); } you are not progressing forward in the linked list. I'm not exactly sure what you intended, but you may want to write as follows to avoid infinite loop... while(result !=null){ System.out.println(j+": "+result.item); result = result.next; j++; } But again if you want to print whole linked list, you should not initialise result with the value returned from removalKthNode function. You should start from first. Hope this makes sense.
You have several issues in your code: 1) The removalKthNode method should return the 1st element in the list to make your code print meaningful results (or you'll have to navigate to the 1st element again to output the remaining list. 2) The while loop which prints your list is wrong in two places. a) You do not increment j, so you always put the same position for the items. b) You do not really iterate through that list, meaning you do not reassign your variable result. Try something like this: int j = 1; while (result != null) { System.out.println(j++ + ": " + result.item); result = result.next; }
The code Node result = removalKthNode(list, k); now result = Third and you have while loop as while(result.next!=null) which is always be in the Third element so it's going for infinite loop. Change the result as below while(result!=null){ System.out.println(j+": "+result.item); result = result.next; }
Try this : Might help you to accompalish the Task: package com.amazon; class Linkedlist{ Node head; public Linkedlist() { head = null; } public Node addNode(int data){ Node newNode = new Node(data); if(head==null) head = newNode; else{ Node current = head; while(current.next!=null){ current = current.next; } current.next = newNode; } return newNode; } } class Node { Node next; int data; Node(int d) { data = d; next = null; } } public class DeleteEveryKthNodes { void modifyList(Node head,int k){ Node current = head; Node previous = null; Node newHead = null; if(current==null)return; int count; while (current != null) { for (count = 1; count < k && current != null; count++) { previous = current; current = current.next; // 1--2--3--4--5 } if (current != null) { Node temp = current; previous.next = current.next; // current = null; temp = null; current = current.next; } } current = head; while(current!=null){ System.out.print(" "+current.data); current = current.next; } } public static void main(String args[]) { Linkedlist list = new Linkedlist(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); new DeleteEveryKthNodes().modifyList(list.head, 2); //list.head.next.next.next.next = new Node(1); } }
Simple Java Script for circular - n=5 and k=3, it will delete every 3 element in circular list. public class TEST { public static int killed_position(int[] newarr,int n,int a,int p) { int iteration=0; while(true) { if(newarr[p-1] != 0) { iteration++; if(iteration>a-1) { break; } } p++; if(p>n) { p=1; } } return p; } public static int next_position(int[] newarr,int n,int a,int p) { int iteration=0; while(iteration<1) { if(newarr[p-1] != 0) { iteration++; } else { p++; if(p>n) { p=1; } } } System.out.println("NEXT START ->" + p); return p; } public static void main(String[] args) { int n=5; int k=3; int newarr[] = new int[n]; int a=1; for(int i=0;i<n;i++) { newarr[i]=i+1; } for(int i=1;i<n;i++) { System.out.println("START -> " + a); a=killed_position(newarr, n,k,a); newarr[a-1]=0; System.out.println("KILLED -> " + a); a=next_position(newarr, n,k,a); System.out.println("---------------------"); } System.out.println("POSITION FINAL MAN -> " + a); System.out.println("POSITION FINAL MAN NAME -> " + a); for(int i=0;i<n;i++) { System.out.print(newarr[i]); } } }