Append two linked list - java

I wrote a simple method to append a linked list at the end of another linked list.So what the program should ideally do is when I give it two lists
list1 ===>1->2->3
list2 ===>4->5->6
updatedList ==>1->2->3->4->5->6
But when I run the method appendList it goes into an infinite loop printing 1 to 6 indefinitely.What am I doing wrong out here?
public static Node appendList(Node head1, Node head2) {
Node prev = null;
Node current = head1;
while (current != null) {
prev = current;
current = current.next;
}
prev.next = head2;
return head1;
}
Oh and I forgot to add the Node class and how I call the method from my main .I know its bit cumbersome but here it is
public class ReverseLinkedList {
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
public void displayData() {
System.out.println(data);
}
}
public static void main(String args[]) {
ReverseLinkedList reversedList = new ReverseLinkedList();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of the linked list!!");
int listSize = scanner.nextInt();
System.out.println("Enter the Numbers you want to insert!!");
int count = 0;
while (scanner.hasNextLine()) {
if (count == listSize)
break;
reversedList.insert(scanner.nextInt());
count++;
}
System.out.println("Inserted List !!");
reversedList.displayList();
/*
* Node reverseNodeStart =
* reversedList.reverseList1(reversedList.first);
* System.out.println("Reversed List !!"); while (reverseNodeStart !=
* null) { reverseNodeStart.displayData(); reverseNodeStart =
* reverseNodeStart.next; }
*/
Node reverseNodeStart = reversedList.appendList(reversedList.first,
reversedList.first);
while (reverseNodeStart != null) {
reverseNodeStart.displayData();
reverseNodeStart = reverseNodeStart.next;
}
}
}

The problem was I was using the same List which was causing the circular reference.It works fine now.You knew the problem even before I posted the code now that's impressive. Thanks!!I solved it by creating a new List2 and passing in List1 and List2.
appendList(Node lis1head, Node list2head)

Related

Linked list is only displaying the head node, not sure why

I am doing a linked list project for my class at school. Essentially we are supposed to make a linked list from scratch, and have add, delete, and find commands. No matter how hard I've been trying I cannot seem to get the list to display anything other than the head node. here are my classes starting from node
public class main {
public static void main(String args[]) {
for (int i = 0; i < 3; i++) {
LinkedList list = new LinkedList();
Node focus = new Node();
String start;
start = JOptionPane.showInputDialog("Enter 'A' to add an item"
+ "\n" + "Enter 'D' to delete an item\nEnter 'F' to find an item.");
if (start.equals("a") || start.equals("A")) {
focus.data = JOptionPane.showInputDialog("enter an item to ADD");
list.Add(focus);
while (focus != null) {
focus = list.head;
focus = focus.next;
JOptionPane.showMessageDialog(null, "your list is\n" + focus.getData());
}
}
}
}
}
public class Node {
String data;
Node next;
Node prev;
public Node(String data, Node next) {
this.data = data;
this.next = next;
}
Node() {
}
public void setData(String data) {
this.data = data;
}
public String getData() {
return this.data;
}
public void setNext(Node next) {//setnext
this.next = next;
}
public Node getNext() {
return next;
}
}
public class LinkedList extends Node {
Node head;
int listcount = 0;
public LinkedList() {
this.prev = null;
this.next = null;
this.listcount = 0;
}
LinkedList(Node Set) {
}
public void Add(Node n) {
Node current = this.prev;
if (current != null) {
current = this.prev;
this.prev = new Node();
} else {
head = this.prev = new Node();
current = head;
}
listcount++;
}
}
I think my biggest problem is the "your list is" part. I can't seem to get it to display anything other than the head node. I would really appreciate the help, as this has been giving me a huge headache. :)
First of all, why does your LinkedList extends the Node class? It's a linked list not a node. There's nothing coming before and after the linked list. So the linked list has no prev and next. All the elements are added in the list and the elements are inserted after the head node. The head of the node has a prev and a next. In the Add method, if the head of the list is null (i.e, the list is empty), the new element becomes the head of the list. Otherwise, the new node is inserted after the head.
public class LinkedList {
Node head;
int listcount = 0;
public LinkedList() {
this.head = null;
this.listcount = 0;
}
public void Add(Node n) {
Node current = this.head;
if (current == null) {
head = n;
} else {
Node prev = null;
while (current != null) {
prev = current;
current = current.next;
}
prev.next = n;
}
listcount++;
}
public String toString() {
StringBuilder builder = new StringBuilder();
Node current = this.head;
while (current != null) {
builder.append(current.data).append(", ");
current = current.next;
}
return builder.toString();
}
}
I added a toString method which loops over the list and builds a string with the content from each node.
In the main method there are a few problems. The linked list is initialised only once not every time you select a choice. If you initialise the linked list every time you select something, then the linked list will always be reinitialised and the only node that will contain will be the head node after you add the new element.
public class main {
public static void main(String args[]) {
String start;
boolean finished=false;
LinkedList list = new LinkedList();
while(!finished) {
start = JOptionPane.showInputDialog("Enter 'A' to add an item"
+ "\n" + "Enter 'D' to delete an item\nEnter 'F' to find an item.");
if (start.equals("a") || start.equals("A")) {
Node focus = new Node();
focus.data = JOptionPane.showInputDialog("enter an item to ADD");
list.Add(focus);
JOptionPane.showMessageDialog(null, "your list is\n" + list.toString());
}
else {
finished = true;
}
}
}
}
Try to go over the code and understand what is happening and why. Also use pencil and paper to understand the logic.

How to duplicate every element of a linked list recursively in Java?

I have to write a duplicate function that duplicates every element of a linked list and returns a linked list such that if L = [2,3,4] then duplicate(L) = [2,2,3,3,4,4]. I have to do this recursively. I realize that below is not the correct solution, but I got confused. =(
public class MyList {
int value;
MyList next;
public static MyList duplicate(MyList L){
if(L.next == null){
L.next.value = L.value;
L.next.next = null;
} else {
MyList temp = L.next;
L.next.value = L.value;
L.next.next = temp;
duplicate(L.next);
}
return L;
}
}
First, check that L isn't an empty list (null). If it contains a value, return a new list that has that value repeated twice, followed by duplicating the rest of the list.
By giving MyList a constructor, this is more readable.
public class MyList {
int value;
MyList next;
public MyList(int value, MyList next) {
this.value = value;
this.next = next;
}
public static MyList duplicate(MyList list) {
if (list == null) {
return null;
} else {
return new MyList(list.value,
new MyList(list.value,
duplicate(list.next)));
}
}
}
You currently add an item and then call the recursion on it, ending at endlessly adding items.
You either need to at elements behind your recursion when processing in a forward-direction, or after the recursion when processing backwards.
Let's create a backwards-direction version. We first recursively walk to the end of the list and then resolve the recursion backwards, adding items after our current element each time.
public <E> void duplicateEntries(MyLinkedList<E> list) {
// Do nothing if list is empty
if (list.size() != 0) {
// Call the recursive method on the head node
duplicateEntriesHelper(list.head);
}
}
public <E> void duplicateEntriesHelper(Node<E> node) {
// Walk to the end of the list
if (node.next != null) {
duplicateEntriesHelper(node.next);
}
// Resolve recursion, duplicate current
// entry by inserting it after the current element
Node<E> duplicatedEntry = new Node<>();
duplicatedEntry.data = node.data;
// Insert element after current node
duplicatedEntry.next = node.next;
node.next = duplicatedEntry;
}
The classes I used should look similar to:
public class MyLinkedList<E> {
public Node<E> head = null;
#Override
public String toString() {
// Build something like "MyLinkedList[2, 3, 4]"
StringBuilder sb = new StringBuilder();
sb.append("MyLinkedList[");
StringJoiner sj = new StringJoiner(",");
Node<E> node = head;
while (node != null) {
sj.add(node);
node = node.next;
}
sb.append(sj);
sb.append("]");
return sb.toString();
}
}
public class Node<E> {
public Node next = null;
public E data = null;
#Override
public String toString() {
return E;
}
}
And here is the demo:
public static void main(String[] args) {
// Setup the list
MyLinkedList<Integer> list = new MyLinkedList<>();
Node<Integer> first = new Node<>();
first.data = 2;
Node<Integer> second = new Node<>();
second.data = 3;
Node<Integer> third = new Node<>();
third.data = 4;
list.head = data;
first.next = second;
second.next = third;
// Demonstrate the method
System.out.println("Before: " + list);
duplicateEntries(list);
System.out.println("After: " + list);
}
Of course you can add additional methods and functionality to them. For example using some constructors or getter/setter methods.

Trouble printing reversed linked list (java)

Basically, I have created methods that print a linked list of integers, delete duplicates from the linked list, as well as invert the linked list. Everything works fine...almost.For some reason, I cannot get my printLinked() method to work after the list has been inverted. For the time being, I just created a while loop to output the reversed list so that I can at least be sure that the list is being reversed. I need to have the printLinked() method do this, though. If anyone can help me out or point me in the right direction in terms of figuring out what the problem is, then I would appreciate it much.
Thank you.
import java.util.Scanner;
public class ListTest
{
public static void main (String[] args)
{
ListNode head = new ListNode();
ListNode tail = head;
tail.link = null;
int input;
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter integers into list; end by entering a zero");
input = keyboard.nextInt();
ListNode temp;
while (input != 0)
{
temp = new ListNode();
temp.data = input;
temp.link = null;
tail.link = temp;
tail = temp;
input = keyboard.nextInt();
}
System.out.println("You entered the following integers : ");
printLinked(head.link);
delrep(head);
System.out.println("After deleting repeating integers, you are left with : ");
printLinked(head.link);
System.out.println("Your inverted list of integers is now : ");
invert(head);
printLinked(head.link);
}
public static void printLinked(ListNode list)
{
ListNode cursor = list;
while (cursor != null)
{
System.out.print(cursor.data + " ");
cursor = cursor.link;
}
System.out.println("");
}
public static void delrep(ListNode head)
{
ListNode temp = new ListNode();
while(head != null)
{
temp = head;
while(temp.link != null)
{
if(head.data == temp.link.data)
{
ListNode temp2 = new ListNode();
temp2 = temp.link;
temp.link = temp2.link;
temp2 = null;
}
else
{
temp = temp.link;
}
}
head = head.link;
}
}
public static void invert(ListNode head)
{
ListNode temp1 = null;
ListNode temp2 = null;
while (head != null)
{
temp1 = head.link;
head.link = temp2;
temp2 = head;
head = temp1;
}
head = temp2;
//This portion of code needs to be removed. I added this part just so I can visually
//confirm that the list is reversing until I can get the print method to work for the
// reversed list.
while (head.link != null)
{
System.out.print(head.data + " ");
head = head.link;
}
System.out.println("");
}
}
also, this is what my ListNode class is:
public class ListNode
{
public int data;
public ListNode link;
}
You need to return the new head of the list at your invert method:
public static ListNode invert(ListNode head) {
ListNode temp1;
ListNode temp2 = null;
while (head != null) {
temp1 = head.link;
head.link = temp2;
temp2 = head;
head = temp1;
}
return temp2;
}
And use the returned value when printing:
System.out.println("Your inverted list of integers is now : ");
ListNode result = invert(head);
printLinked(result.link);
It wasn't printing because you were using the original head that was now the tail of the list.

Remove duplicates from an unsorted linked list

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

Java Linked List Sorting

So the app reads from an external file a bunch of strings, each on a separate line.
For example:
and
cake
here
It is not arranged in any particular order. I need to read these letters and put them into linked list and finally sort them.
I need help on doing that:
Here is the current code:
import java.util.*;
import java.io.*;
public class LinkedList
{
static File dataInpt;
static Scanner inFile;
public static void main(String[] args) throws IOException
{
dataInpt=new File("C:\\lldata.txt");
inFile=new Scanner(dataInpt);
Node first = insertInOrder();
printList(first);
}
public static Node getNode(Object element)
{
Node temp=new Node();
temp.value=element;
temp.next=null;
return temp;
}
public static void printList(Node head)
{
Node ptr; //not pointing anywhere
for(ptr=head;ptr!=null;ptr=ptr.next)
System.out.println(ptr.value);
System.out.println();
}
public static Node insertInOrder()
{
Node first=getNode(inFile.next());
Node current=first,previous=null;
Node last=first;
int count=0;
while (inFile.hasNext())
{
if (previous!=null
&& ((String)current.value).compareTo((String)previous.value) > 0)
{
last.next=previous;
previous=last;
}
if (previous!=null
&& ((String)current.value).compareTo((String)previous.value) < 0)
{
current.next=last;
last=current;
}
previous=current;
current=getNode(inFile.next());
}
return last;
}
}
But that gives an infinite loop with "Cat".
Here is the data file:
Lol
Cake
Gel
Hi
Gee
Age
Rage
Tim
Where
And
Kite
Jam
Nickel
Cat
Ran
Jug
Here
Okay, self-study. Split the reading and inserting. Though old and new code both have 14 lines of code,
it makes it more intelligable.
public static Node insertInOrder() {
Node first = null;
while (inFile.hasNext()) {
String value = inFile.next().toString();
first = insert(first, value);
}
return first;
}
/**
* Insert in a sub-list, yielding a changed sub-list.
* #param node the sub-list.
* #param value
* #return the new sub-list (the head node might have been changed).
*/
private static Node insert(Node node, String value) {
if (node == null) { // End of list
return getNode(value);
}
int comparison = node.value.compareTo(value);
if (comparison >= 0) { // Or > 0 for stable sort.
Node newNode = getNode(value); // Insert in front.
newNode.next = node;
return newNode;
}
node.next = insert(node.next, value); // Insert in the rest.
return node;
}
This uses recursion (nested "rerunning"), calling insert inside insert. This works like a loop, or work delegation to a clone, or like a mathematical inductive proof.
Iterative alternative
also simplified a bit.
private static void Node insert(Node list, String value) {
Node node = list;
Node previous = null;
for (;;) {
if (node == null || node.value.compareTo(value) >= 0) {
Node newNode = getNode(value);
newNode.next = node;
if (previous == null)
list = newNode;
else
previous.next = newNode;
break;
}
// Insert in the rest:
previous = node;
node = node.next;
}
return list;
}
public static Node insertInOrder()
{
Node first=getNode(inFile.next());
Node current=first,previous=null;
Node last=first;
int count=0;
while (inFile.hasNext())
{
if (previous!=null
&& ((String)current.value).compareTo((String)previous.value) > 0)
{
last.next=previous;
previous=last;
}
if (previous!=null
&& ((String)current.value).compareTo((String)previous.value) < 0)
{
current.next=last;
last=current;
}
previous=current;
current=getNode(inFile.next());
}
return last;
}
First of all, you never do anything with the last line read from the file, so that's not ever inserted. You have to read the line and create the new Node before relinking next pointers.
Then, if last and previous refer to the same Node and the data of current is larger than that of previous,
if (previous!=null
&& ((String)current.value).compareTo((String)previous.value) > 0)
{
last.next=previous;
previous=last;
}
You set last.next = last, breaking the list. From the code (in particular the absence of a sort(Node) function), it seems as though you want to sort the list as it is created. But you only ever compare each new Node with one other, so that doesn't maintain order.
For each new node, you have to find the node after which it has to be inserted, scanning from the front of the list, and modify current.next and the predecessor's next.
In relatively simple code like that in your question, a good exercise to understanding it is to work through a few interations of your loop, inspecting the values of all your local variable to see the effect of your code. You can even do it by hand if the code is simple. If it is too difficult to do by hand, your code is probably too complicated. If you can't follow it, how can you know if you are doing what you intend. For example, I could be wrong, but this appears the be the state at the top of each iteration of the loop. It starts falling apart on the third time through, and by the fourth you have a severe problem as your list becomes disjointed.
1)last = first = Lol, current = previous = null
Lol->null
2)last = first = previous = Lol, current = Cake
Lol->Lol
3)first = Lol, last = Cake, previous = Cake, current = Gel
Cake->Lol->Lol
4)first = Lol, last = Cake, previous = Cake, current = Hi
Cake->Gel, Lol->Lol
Quite honestly, if I were running the course, I would consider the correct answer to be:
List<String> list = new LinkedList<String>();
// read in lines and: list.add(word);
Collections.sort(list);
Ok, I don't remember exactly school theory about insertion sort, but here is somehow a mix of what I think it is and your code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class LinkedList {
public static class Node {
public String value;
public Node next;
}
static File dataInpt;
static Scanner inFile;
public static void main(String[] args) throws IOException {
inFile = new Scanner("Lol\r\n" + "Cake\r\n" + "Gel\r\n" + "Hi\r\n" + "Gee\r\n" + "Age\r\n" + "Rage\r\n" + "Tim\r\n" + "Where\r\n"
+ "And\r\n" + "Kite\r\n" + "Jam\r\n" + "Nickel\r\n" + "Cat\r\n" + "Ran\r\n" + "Jug\r\n" + "Here");
Node first = insertInOrder();
printList(first);
}
public static Node getNode(String element) {
Node temp = new Node();
temp.value = element;
temp.next = null;
return temp;
}
public static void printList(Node head) {
Node ptr; // not pointing anywhere
for (ptr = head; ptr != null; ptr = ptr.next) {
System.out.println(ptr.value);
}
System.out.println();
}
public static Node insertInOrder() {
Node current = getNode(inFile.next());
Node first = current, last = current;
while (inFile.hasNext()) {
if (first != null && current.value.compareTo(first.value) < 0) {
current.next = first;
first = current;
} else if (last != null && current.value.compareTo(last.value) > 0) {
last.next = current;
last = current;
} else {
Node temp = first;
while (current.value.compareTo(temp.value) < 0) {
temp = temp.next;
}
current.next = temp.next;
temp.next = current;
}
current = getNode(inFile.next());
}
return first;
}
}
And it works like a charm. Of course this far from optimal, both in terms of performance and code reuse.

Categories

Resources