i have one problem with my code ,i did a sample program to display the emp details from a linked list,now the problem when i trying to delete a particular entry means it doesn't work,i hope i did some mistake in my code could you suggest how to do that?
import java.util.*;
class EmpDedup {
int record;
String fprint;
int fid;
EmpDedup(int record, String fprint, int fid) {
this.record = record;
this.fprint = fprint;
this.fid = fid;
}
public int getRecord() {
return record;
}
public String getFprint() {
return fprint;
}
public int getFid() {
return fid;
}
public static void main(String[] args) {
int count = 0;
LinkedList<EmpDedup> list = new LinkedList<EmpDedup>();
list.add(new EmpDedup(101, "entry1", 20));
list.add(new EmpDedup(102, "entry2", 30));
list.add(new EmpDedup(103, "entry3", 40));
list.add(new EmpDedup(104, "entry4", 50));
Scanner input = new Scanner(System.in);
System.out.print("Enter record no to display: ");
int rec = input.nextInt();
for (EmpDedup data : list) {
if (data.getRecord() == rec) {
System.out.println(data.getRecord() + "\t" + data.getFprint() + "\t" + data.getFid() + "\t");
count++;
}
}
System.out.println("The size of an linkedlist is: \t" + list.size());
System.out.println("The number of available record is :" + count);
System.out.println("The size of an linkedlist is: \t" + list.size());
Scanner input1 = new Scanner(System.in);
System.out.print("Enter record no to delete: ");// here i try to delete a particular record
int rec1 = input1.nextInt();
for (EmpDedup data : list) {
if (data.getRecord() == rec1) {
// System.out.println(data.getRecord()+"\t"+data.getFprint()+"\t"+data.getFid()+"\t");
list.remove(data); // problem is here
count++;
}
}
}
}
you cannot operate in lists (add, remove... items) while you iterate on them. You have to use an Iterator
for(Iterator<EmpDedup> iter = list.iterator(); iter.hasNext();) {
EmpDedup data = iter.next();
if (data.getRecord() == rec1) {
iter.remove();
}
}
see http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html
Use an Iterator instead and then use the remove() method on the Iterator
When you do this:
list.remove(101);
you are calling this method, which will not serve your purpose.
You should rather use:
list.remove(data);
You try to delete element with index 101, but you have only 4 items in list. How it can delete element with index 101?
If you want to delete element that is equals to EmpDedup(101,"entry1",20) than you have to pass in remove method this object. And don't foget to redefine equals and hash code of EmpDedup.
The code tries to remove element at index position 101, but there are only four items in the list.
Use the following as a replacement of your code:
for( EmpDedup data : list)
{
if( data.getRecord() == rec1 )
{
list.remove( data );
++count;
}
}
That's where a list object will be deleted.
for( EmpDedup data:list)
{
if(data.getRecord()==rec1)
{
list.remove(data);
count++;
}
}
import java.util.Scanner;
// A complete working Java program to demonstrate deletion in singly
// linked list
class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Given a key, deletes the first occurrence of key in linked list */
void deleteNode(int key)
{
// Store head node
Node temp = head, prev = null;
// If head node itself holds the key to be deleted
if (temp != null && temp.data == key)
{
head = temp.next; // Changed head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.data != key)
{
prev = temp;
temp = temp.next;
}
// If key was not present in linked list
if (temp == null) return;
// Unlink the node from linked list
prev.next = temp.next;
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
/* This function prints contents of linked list starting from
the given node */
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}
/* Drier program to test above functions. Ideally this function
should be in a separate user class. It is kept here to keep
code compact */
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
System.out.println("\nCreated Linked list is:");
llist.printList();
Scanner sc = new Scanner(System.in);
System.out.println("please enter input");
int aa =sc.nextInt();
llist.deleteNode(aa); // Delete node at position 4
System.out.println("\nLinked List after Deletion at position :"+aa);
llist.printList();
System.out.println("adding element to the LinkedList");
System.out.println("enter element");
int dd = sc.nextInt();
llist.push(dd);
llist.printList();
}
}
Related
Given a linked list, delete N nodes after skipping M nodes of a linked list until the last of the linked list
This is the Java program I wrote to solve this problem. For certain large test cases it's showing error,
"Exception in thread "main" java.lang.NullPointerException: Cannot assign field "next" because "" is null
at SinglyLinkedList.deleteNNodesAfterEveryMNodes(DeleteNNodesAfterMNodesOfALinkedList.java:88)
at DeleteNNodesAfterMNodesOfALinkedList.main(DeleteNNodesAfterMNodesOfALinkedList.java:127)"
import java.io.*;
import java.util.*;
class Link
{
public int data;
public Link next;
public Link(int d)
{
data = d;
}
public void displayLink()
{
System.out.print(data + " ");
}
}
class SinglyLinkedList
{
public Link first;
public SinglyLinkedList()
{
first = null;
}
public boolean isEmpty()
{
return(first == null);
}
public void insertLast(int d)
{
Link nl = new Link(d);
if(isEmpty())
{
first = nl;
}
else
{
Link curr = first;
while(curr.next != null)
{
curr = curr.next;
}
curr.next = nl;
}
}
public void displayList()
{
Link curr = first;
while(curr != null)
{
curr.displayLink();
curr = curr.next;
}
}
public void deleteNNodesAfterEveryMNodes(int N, int M)
{
Link curr1=first, curr2=first;
int n=N+M, m=M;
while(curr1!=null && curr1.next!=null)
{
while(curr2!=null && n!=0)
{
if(m != 1)
{
curr1 = curr1.next;
m--;
}
curr2 = curr2.next;
n--;
}
curr1.next = curr2;
m = M;
n = N+M;
curr1 = curr2;
}
}
}
class DeleteNNodesAfterMNodesOfALinkedList
{
public static void main(String st[])
{
Scanner sc = new Scanner(System.in);
SinglyLinkedList sll = new SinglyLinkedList();
int count, d, N, M;
System.out.println("Enter the number of integers you want to store in the singly linked list: ");
count = sc.nextInt();
System.out.println("\nEnter the " + count + " integers: ");
for(int i=0; i<count; i++)
{
d = sc.nextInt();
sll.insertLast(d);
}
System.out.println("\nThe singly linked list is: ");
sll.displayList();
System.out.println("\n\nEnter the value of 'M', the number of nodes to be skipped: ");
M = sc.nextInt();
System.out.println("\nEnter the value of 'N', the number of nodes now to be deleted: ");
N = sc.nextInt();
sll.deleteNNodesAfterEveryMNodes(N, M);
System.out.println("\nThe resultant singly linked list is: ");
sll.displayList();
}
}
I can't figure out what went wrong and how is assigning curr1.next = curr2; is of any issue at line 127
You can either try to put an additional check of curr1!=null in the second while loop or simplify the problem.
Simplifying the problem can be done by:
Using a for loop (m number of times) to traverse the list.
Using another for loop (n number of times) to call a piece of code that deletes the nodes one by one.
Also check for edge conditions i.e. if m + n < size and so on.
The following is my console log output... The user inputs the integers to add, and the index of the element they wish to switch:
enter integer to add: 4
enter another integer to add: 5
enter another integer to add: 6
enter another integer to add: 7
enter another integer to add: 8
Nodes of doubly linked list:
4 5 6 7 8
enter the index of the element that you would like to swap: 2
Nodes of doubly linked list:
4 5 6 7 8
...But of course this last line should say 45768
package ass1Q2A;
public class SLList {
public SLNode head = null;
public SLNode tail = null;
public void add(int a) { //adds new element to our single-linked list.
SLNode newNode = new SLNode(a);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
//THIS SLSWAP METHOD IS WHERE I THINK THE ERROR IS:
public void SLswap(int i) throws illegalOperation { //i is index of node to change. method swaps specified node of index "i" with following node.
if(i>=(size()-1))
throw new illegalOperation("must swap one of the nodes, OR there does not exist node after tail");
if (size() < 2)
throw new illegalOperation("cant swap if theres less than two elements");
else if (size() == 2) {
SLNode placeholder = tail;
tail = head;
head = placeholder;
} // end else if
else { //LOGICAL ERROR MUST EXIST IN THIS ELSE STATEMENT
SLNode iterationNode = head;
for (int j = 0; j<i; i++) {//order of pointing: iterationNode => iterationNode.next => nodeB => iterationNode.next.next.NEXT
if (j==(i-1)) { //GOAL: swap iterationNode.next with nodeB(iteraitonNode.next.next)
SLNode nodeB = iterationNode.next.next;
iterationNode.next.next = iterationNode.next.next.next;
nodeB.next = iterationNode.next;
iterationNode.next = nodeB;
break;
}
iterationNode = iterationNode.next; //iterate to next node
} // end for-loop
}
}
public int size() {//returns number of nodes in SingleLinkedList
SLNode u = head;
int size = 0;
while (u != null) {
size++;
u = u.next;
}
return size;
}
public void display() { //prints values of all nodes in SLL, starting from head
SLNode current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of doubly linked list: ");
while(current != null) {
//Prints each node by incrementing the pointer.
System.out.print(current.data + " ");
current = current.next;
}
}
public static void main(String[] args) {
//EVERYTHING WORKS BUT SWAP METHOD... LOGICAL ERROR?
SLList myList = new SLList();
//Add nodes to the list
int toAdd1 = IOHelper.getInt("enter integer to add:");
int toAdd2 = IOHelper.getInt("enter another integer to add:");
int toAdd3 = IOHelper.getInt("enter another integer to add:");
int toAdd4 = IOHelper.getInt("enter another integer to add:");
int toAdd5 = IOHelper.getInt("enter another integer to add:"); //completed prompting user for input data for SinglyLinkedList
myList.add(toAdd1);
myList.add(toAdd2);
myList.add(toAdd3);
myList.add(toAdd4);
myList.add(toAdd5); //completed adding user-inputted data to SinglyLinkedList
myList.display(); //Displays the nodes present in the SLList before any swapping takes place
int indexToSwap = IOHelper.getInt("enter the index of the element that you would like to swap:"); //prompt user for index he/she wishes to swap
try {
try {
myList.SLswap(indexToSwap); //call SLSwap with user-inputted index
}catch(NullPointerException i) {};
}catch(illegalOperation e) {};
myList.display(); //display list after the switch
}
}
public class SLNode {
int data; //data that a node holds
SLNode next; // next node in the SSList that this given node will point to
public SLNode(int data) {
this.data = data;
this.next = null;
}
}
Write a Java program to move the last element of the linked list in the front and rest of the element by one position, and then print the modified linked list.
NOTE: Remember you cannot use the LinkedList java class and its methods, you have to make your own LinkedList class and methods.
I have written the code to move the last node to the first but ii'm not able to delete the node whichever I wanted.
import java.util.*;
public class LinkedList {
Node head;
class Node
{
int data ;
Node next;
Node(int a )
{
data = a ;
next = null;
}
}
void movefront()
{
if(head == null || head.next == null)
return;
Node secLast = null;
Node last = head;
while(last.next!= null)
{
secLast = last;
last = last.next;
}
secLast.next=null;
last.next = head;
head = last;
}
void deleteNode(int key)
{
// Store head node
Node temp = head, prev = null;
// If head node itself holds the key to be deleted
if (temp != null && temp.data == key)
{
head = temp.next; // Changed head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.data != key)
{
prev = temp;
temp = temp.next;
}
// If key was not present in linked list
if (temp == null) return;
// Unlink the node from linked list
prev.next = temp.next;
}
public void push (int new_data)
{
Node new_node = new Node(new_data);
new_node.next= head;
head = new_node;
}
void printList()
{
Node temp = head;
while(temp!=null)
{
System.out.println(temp.data + " ");
temp = temp.next;
} System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Number of integers to be enetered in the list:");
Scanner sc = new Scanner(System.in);
LinkedList llist = new LinkedList();
Integer n= sc.nextInt();
Integer arr[]=new Integer[n];
System.out.println("Insert the elements of your array");
for(int i=0; i<=arr.length; i++)
{
n= sc.nextInt();
llist.push(n);
}
System.out.println(" Linked list before moving last to front : " );
llist.printList();
llist.movefront();
llist.deleteNode(2);
System.out.println(" Linked list after moving from front to last : ");
llist.printList();
}
}
Try:
public class LinkedList {
static Scanner sc = new Scanner(System.in);
Node head;
class Node
{
int data ;
Node next;
Node(int a )
{
data = a ;
next = null;
}
}
void movefront()
{
if(head == null || head.next == null)
return;
Node secLast = null;
Node last = head;
while(last.next!= null)
{
secLast = last;
last = last.next;
}
secLast.next=null;
last.next = head;
head = last;
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next= null;
if(head == null) {
head = new_node;
return;
}
Node last_Node = head;
while(last_Node.next != null) {
last_Node = last_Node.next;
}
last_Node.next = new_node;
}
void printList()
{
Node temp = head;
while(temp != null)
{
System.out.println(temp.data + " ");
temp = temp.next;
} System.out.println();
}
private void delete() {
Node current_Node = head;
if(current_Node == null) {
System.out.println("no element in list to be deleted");
return;
}
head = current_Node.next;
}
public static void main(String[] args) {
System.out.println("Number of integers to be entered in the list:");
LinkedList llist = new LinkedList();
Integer n= sc.nextInt();
Integer arr[]=new Integer[n];
System.out.println("Insert the elements of your array: ");
for(int i=0; i<arr.length; i++)
{
n= sc.nextInt();
llist.push(n);
}
System.out.println("Linked list before moving last to front: " );
llist.printList();
llist.movefront();
System.out.println("Linked list after moving from front to last: ");
llist.printList();
System.out.println("Deleting first element from the list: ");
llist.delete();
llist.printList();
}
}
Output:
Explanation:
Updated for(int i=0; i<=arr.length; i++) to for(int i=0; i<arr.length; i++) in main method as index start from 0 so it should go till arr.length-1 hence i<arr.length.
Updated push method. New node is inserted at the end of the linkedlist but in your code it was acting as stack.
Added delete method to remove first node. If head is null in that case list is empty hence no element can be removed from the list. If it contains element then head will point to current_Node.next;
Hello fellow Programmers!
I would like to ask how to implement the Search Function in Singly Linked List using Java (Data Structures).
PROBLEM: The Search function of my program can only access the head and tail of the elements.
Question: How can I access all the elements?
Sample Code:
import java.util.*;
public class MyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
public void add(T element){
Node<T> nd = new Node<T>();
nd.setValue(element);
if(head == null){
head = nd;
tail = nd;
}
else {
tail.setNextRef(nd);
tail = nd;
}}
public void delete(){
if(head == null){
System.out.println("List is empty...");
}
else{
Node<T> tmp = head;
head = tmp.getNextRef();
if(head == null){
tail = null;
}
System.out.println("Deleted: "+tmp.getValue());
System.out.println("First Employee Name Deleted!");
}
}
public void search(){
Node<T> tmp = head;
if(head==null){
System.out.println("List is empty...");
}
else{
String b=""+tmp.getValue();
Scanner input=new Scanner(System.in);
System.out.print("Enter an employee name to search: ");
String search = input.nextLine();
if(b.equals(search)){
System.out.println("Found! "+tmp.getValue());
}
else if (b!=search){
System.out.println("Not Found!");
}
tmp = tmp.getNextRef();
} }
public void show(){
Node<T> tmp = head;
if(head==null){
System.out.println("List is empty...");
}
else{
while(true){
if(tmp == null){
break;
}
System.out.println(tmp.getValue());
tmp = tmp.getNextRef();
}}
}
public static void main(String a[]){
MyLinkedList<String> sl = new MyLinkedList<String>();
Scanner input = new Scanner(System.in);
sl.add("Garcia, Bianca Axel, 001");
sl.add("Temprosa, Camille Ann, 002");
sl.add("Villanueva, Von Justin, 003");
sl.add("Rivera, Reygie, 004");
sl.add("Dapapac, Ronnelle, 005");
sl.add("Bati, Aubrey, 006");
sl.add("Fiestada, Diana Rose, 007");
sl.add("Dobalada, Jojo, 008");
sl.add("Del Mundo, Maria Ethel, 009");
sl.add("Alejandro, Rachelle, 010");
System.out.print("Welcome To Singly Linked List Management for Employee Names!\n(Created by: Alex del Rosario || Source Code: Mr. John Carlo Son)\n");
while(true){
System.out.println("*------------------------*");
System.out.println("*PLEASE SELECT A FUNCTION*");
System.out.println("*1.)Add Employee Name *");
System.out.println("*2.)Delete Employee Name *");
System.out.println("*3.)Show Employee List *");
System.out.println("*4.)Search an Employee *");
System.out.println("*5.)Exit the program *");
System.out.println("*------------------------*");
System.out.print("Enter a number: ");
int select = input.nextInt();
if(select==1){
System.out.println("**Enter an employee name with ID number**");
System.out.println("Use this format:(Last Name),(First Name),(ID number)");
System.out.println("(ex. del Rosario, Alex, 0001)");
System.out.print("Input here: ");
input.nextLine();
String employee=input.nextLine();
sl.add(employee);
System.out.println("Employee: "+employee+" successfully added!");
}
else if(select==2){
sl.delete();
}
else if(select==3){
System.out.println("Employee List:");
sl.show();
}
else if(select==4){
sl.search();
}
else if(select==5){
System.out.println("*** THANK YOU FOR USING THIS PROGRAM! :) ***");
System.exit(0);
}
else{
System.out.println("INVALID INPUT!");
}
}}
}
class Node <T> implements Comparable<T> {
private T value;
private Node<T> nextRef;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNextRef() {
return nextRef;
}
public void setNextRef(Node<T> ref) {
this.nextRef = ref;
}
#Override
public int compareTo(T arg) {
if(arg == this.value){
return 0;
} else {
return 1;
}
}
}
More a tipp than an answer. Ask yourself what you want to do. Do you want to use the linked list provided by Java or write your own code for a linked list?
With the provided list iterating is easy.
private void search(String searchElement) {
for (int i = 0; i < list.size(); i++) {
String listElement = list.get(i);
if (searchElement.equals(listElement)) {
System.out.println("Found element " + searchElement + " at position " + i);
return;
}
}
System.out.println(searchElement + " does not appear in the list");
}
When writing your own list you have to be more careful how you use the list. For example your implementation of delete() will not work.
public void delete(){
if(head == null){
System.out.println(List is empty...);
}
else{
NodeAlex tmp = head;
head = tmp.getNextRef();
if(head == null){ // you need to check if head == tail or head.getNextRef() == null
tail = null; // here you have to set tmp.setNextRef(null);
// and additionally define tmp as tail.
}
System.out.println(Deleted +tmp.getValue());
System.out.println(First Employee Name Deleted!);
}
}
Edit: To access the list you have two possibilities. At first you have to create a new instance, i.e., (here for Strings, you might want to use other types/objects)
List<String> list = new LinkedList<String>();
Then you basically have two opportunities on how to access the list in the methods.
(a) Your method is in the same class where you initialized the list, however, list has to be a global field.
private List<String> list;
private static void main(String[] args) {
list = new LinkedList<String>();
(...)
}
private static void search(String searchElement) {
// has access on list
}
(b) You simply pass your list to the method you need and if the method modifies the list you need to return the list again.
(main class, main method)
search(list, "Test");
list = delete(list, "Test");
(the class where the methods are located)
public void search(List<String> list, String searchElement) { ... }
public List<String> delete(List<String> list, String elementToDelete) {
// delete element
return list;
}
HI :) I have a program about linked lists and we're supposed to be able to delete two numbers if they are the same.. and i know how to do it from the start but how do you delete two numbers if they are in the middle of the linked list?? All 3 run together
Heres my numbers program
import java.util.Scanner;
public class Numbers {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner (System.in);
LinkedList link=new LinkedList();
LinkedList link2= new LinkedList();
System.out.println("Enter in 5 numbers to put in your list");
int num1, num2, num3, num4, num5;
num1 = reader.nextInt();
link.addToStart(num1);
num2 = reader.nextInt();
link.addToStart(num2);
num3 = reader.nextInt();
link.addToStart(num3);
num4 = reader.nextInt();
link.addToStart(num4);
num5 = reader.nextInt();
link.addToStart(num5);
link2.addToStart(num5);
link2.addToStart(num4);
link2.addToStart(num3);
link2.addToStart(num2);
link2.addToStart(num1);
System.out.println("The size of the linked list is " + link.size());
System.out.print("Here is the list ");
link2.outputList();
System.out.println();
System.out.print("Here is the list in reverse order ");
link.outputList( );
System.out.println();
if (num1==num2){
link2.deleteHeadNode(num1);
link2.deleteHeadNode(num2);
System.out.println("Here is the list with the removed numbers");
link2.outputList();
System.out.println();
System.out.println("Here is its size");
System.out.println(link2.size());
}
else if (num2==num3){
link2.deleteHeadNode(num2);
link2.deleteHeadNode(num3);
System.out.println("Here is the list with the removed numbers");
link2.outputList();
System.out.println();
System.out.println("Here is its size");
System.out.println(link2.size());
}
}
}
Here is the node program
public class Node1
{
private Object item;
private int count;
private Node1 link;
public Node1( )
{
link = null;
item = null;
count = 0;
}
public Node1(int num, int newCount, Node1 linkValue)
{
setData(num, newCount);
link = linkValue;
}
public void setData(int num, int newCount)
{
item = num;
count = newCount;
}
public void setLink(Node1 newLink)
{
link = newLink;
}
public Object getItem( )
{
return item;
}
public int getCount( )
{
return count;
}
public Node1 getLink( )
{
return link;
}
}
And here is linked lists program
public class LinkedList
{
private Node1 head;
public LinkedList( )
{
head = null;
}
/**
Adds a node at the start of the list with the specified data.
The added node will be the first node in the list.
*/
public void addToStart(int num)
{
head = new Node1(num, num, head);
}
/**
Removes the head node and returns true if the list contains at least
one node. Returns false if the list is empty.
* #param num1
*/
public boolean deleteHeadNode(int num1 )
{
if (head != null)
{
head = head.getLink( );
return true;
}
else
return false;
}
/**
Returns the number of nodes in the list.
*/
public int size( )
{
int count = 0;
Node1 position = head;
while (position != null)
{
count++;
position = position.getLink( );
}
return count;
}
public boolean contains(String item)
{
return (find(item) != null);
}
/**
Finds the first node containing the target item, and returns a
reference to that node. If target is not in the list, null is returned.
*/
private Node1 find(String target)
{
Node1 position = head;
Object itemAtPosition;
while (position != null)
{
itemAtPosition = position.getItem( );
if (itemAtPosition.equals(target))
return position;
position = position.getLink( );
}
return null; //target was not found
}
public void outputList( )
{
Node1 position = head;
while (position != null)
{
System.out.print(position.getItem( ) + " ");
position = position.getLink( );
}
}
public boolean isEmpty( )
{
return (head == null);
}
public void clear( )
{
head = null;
}
}
To remove an item in the middle of the linked list, set the previous item's "link" pointer to the "link" pointer of the object you want to remove. For instance, you could add something like this to your LinkedList class:
public void removeNode(Node previousNode, Node nodeToRemove) {
if (previousNode != null) {
previousNode.setLink(nodeToRemove.getLink());
}
}
To think about this better, draw a picture.
N1 -> N2 -> N3 -> N4
N1's "link" is N2, etc. If you want to remove N2, just set N1's "link" to N3.
N1 -> N3 -> N4
One approach it to perform a brute force look up.
For each element you search if is repeated in the list.
If it is, you remove it
and go with the next.
As you may see these three steps may be coded quite easy, the point here is to first understand if they do what you want.
This is the pseudo-code for these three points:
forEach( Element a : inList ) do
// e is the element we want to find repeated.
forEach( Element b : inList ) do
// b is the element in the list.
if( a == b ) then // repeated
inList.remove( a )
break;
endIf
endFor
endFor
This approach will allow you to remove all the repeated elements.
Just remember to remove one item, you have to make sure you don't lose the reference it has. So if you have:
n1 -> n2 -> n3
at some point you have to have n1 and n2 pointing to n3 ( that way n1 keeps the reference n2 has )
n1 -> n3 n2 ->n3
and then remove n2 which leaves you:
n1 -> n3
Now how to code that with your specific data structure is a task you have to perform ;)
Here is a way to do it.
public void delete(int item)
{
while(head.data==item) //For deleting head
{
head=head.link;
}
// For middle elements..................
Node ptr, save;
save=head;
ptr=head.link;
while(ptr!=null)
{
if(ptr.data==item)
{
Node next=ptr.link;
save.link=next;
ptr=next;
}
else
{
save=ptr;
ptr=ptr.link;
}
}
}