Problem Searching a Linked List
Hi, I'm trying to take an input string and compare it with the string that is returned when a "getName" method is called on my linked list but it is giving me a runtime error. The code is below. Can anyone give me any ideas as to what I'm doing wrong. Thanks.
private void searchItemList(String searchItem)//method to search for an item
System.out.println("Entry into searchItemList method");
boolean itemFound;
this.searchItem = JOptionPane.showInputDialog(null, "Type in a Key word to search", "Search List",
JOptionPane.QUESTION_MESSAGE);
ListIterator librarySearch = Library.libraryList.listIterator();
while(librarySearch.hasNext())
LibraryItems searchList = (LibraryItems) librarySearch.next();
System.out.println(searchList.getItemName());
JOptionPane.showMessageDialog(null,"Message","message",JOptionPane.ERROR_MESSAGE);//it works up to here
if(searchItem.equalsIgnoreCase(searchList.getItemName()))//this is where the error occurs
JOptionPane.showMessageDialog(null, "Item Found", "Message",JOptionPane.INFORMATION_MESSAGE);
else {
JOptionPane.showMessageDialog(null, "Item not found", "message",JOptionPane.INFORMATION_MESSAGE);
System.out.println("Exit from searchItemList method");
}
Hi, Okay I've only been able to capture half of the stack trace (I don't know how to capture the full stack).
This is it below:
at java.awt.Component.processMouseEvent(Component.java:5093)
at java.awt.Component.processEvent(Component.java:4890)
at java.awt.Container.processEvent(Container.java:1566)
at java.awt.Component.dispatchEventImpl(Component.java:3598)
at java.awt.Container.dispatchEventImpl(Container.java:1623)
at java.awt.Component.dispatchEvent(Component.java:3439)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
at java.awt.Container.dispatchEventImpl(Container.java:1609)
at java.awt.Window.dispatchEventImpl(Window.java:1585)
at java.awt.Component.dispatchEvent(Component.java:3439)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
I'm not sure if it will be of any help, if it isn't thanks anyway.
Jay.
Similar Messages
-
Urgent problem : array of linked list
In order to save memory I am trying to build an array of linkedlist with the following program. It compiles well but when I execute it, error occurs as follows,
Exception in thread "main" java.lang.NullPointerException
at testLL2.main(testLL2.java:10)
My program:
import java.net.*;
import java.io.*;
import java.util.LinkedList;
public class testLL2 {
public static void main(String[] args) throws IOException {
int myLLLength;
LinkedList myLL2 [] = new LinkedList[10];
for (int i = 0; i < 10; i++) {
for (int j=0; j < 5; j++) {
myLL2.add(" "+j);
for (int i = 0; i < 10; i++) {
myLLLength = myLL2[i].size();
for (int j=0; j<myLLLength; j++) {
System.out.println(myLL2[i].get(j));
Since I tried many alternatives to solve it but one of them succeed. Please kindly help me! Thanks in advance![snip]
2. Where you have 'myLL2.add(" "+j);' it should read
myLL2. The is probably a typo. If not, make sure
you understand why you need to change your code.
The forum posting code will muck up your code if you don't surround it in [ code] [code ] (no spaces) tags. Even if you do use the code tags, it preprocesses [ i] into <i> to avoid turning your code into italics. -
Help with linked lists and searching
Hi guys I'm very new to java. I'm having a problem with linked lists. the program's driver needs to create game objects, store them, be able to search the linked list etc. etc. I've read the API but I am really having trouble understanding it.
First problem is that when I make a new game object through the menu when running the program, and then print the entire schedule all the objects print out the same as the latest game object created
Second problem is searching it. I just really have no idea.
Here is the driver:
import java.util.*;
public class teamSchedule
public static void main (String[]args)
//variables
boolean start;
game game1;
int selector;
Scanner scanner1;
String date = new String();
String venue = new String();
String time = new String();
String dateSearch = new String();
double price;
String opponent = new String();
int addindex;
List teamSchedLL = new LinkedList();
String dateIndex = new String();
String removeYN = new String();
String venueIndex = new String();
String opponentIndex = new String();
start = true; //start makes the menu run in a while loop.
while (start == true)
System.out.println("Welcome to the Team Scheduling Program.");
System.out.println("To add a game to the schedule enter 1");
System.out.println("To search for a game by date enter 2");
System.out.println("To search for a game by venue enter 3");
System.out.println("To search for a game by opponent enter 4");
System.out.println("To display all tour information enter 5");
System.out.println("");
System.out.println("To remove a game from the schedule enter search for the game, then"
+ " remove it.");
System.out.println("");
System.out.println("Enter choice now:");
scanner1 = new Scanner (System.in);
selector = scanner1.nextInt();
System.out.println("");
if (selector == 1)
//add a game
scanner1.nextLine();
System.out.println("Adding a game...");
System.out.println("Enter game date:");
date = scanner1.nextLine();
System.out.println("Enter game venue:");
venue = scanner1.nextLine();
System.out.println("Enter game time:");
time = scanner1.nextLine();
System.out.println("Enter ticket price:");
price = scanner1.nextDouble();
scanner1.nextLine();
System.out.println("Enter opponent:");
opponent = scanner1.nextLine();
game1 = new game(date, venue, time, price, opponent);
teamSchedLL.add(game1);
System.out.println(teamSchedLL);
System.out.println("Game created, returning to main menu. \n");
start = true;
else if (selector == 2)
//search using date
scanner1.nextLine();
System.out.println("Enter the date to search for in the format that it was entered:");
dateIndex = scanner1.nextLine();
if (teamSchedLL.indexOf(dateIndex) == -1)
System.out.println("No matching date found. Returning to main menu.");
start = true;
else
//give user option to remove game if they wish.
System.out.println(teamSchedLL.get(teamSchedLL.indexOf(dateIndex)));
System.out.println("Would you like to remove this game? Y/N");
removeYN = scanner1.nextLine();
if (removeYN == "Y" || removeYN == "y")
teamSchedLL.remove(teamSchedLL.indexOf(dateIndex));
System.out.println("Scheduled game removed.");
System.out.println("\n Returning to main menu. \n");
start = true;
else if (selector == 3)
//search using venue name
scanner1.nextLine();
System.out.println("Enter the venue to search for in the format that it was entered:");
venueIndex = scanner1.nextLine();
if (teamSchedLL.indexOf(venueIndex) == -1)
System.out.println("No matching venue found. Returning to main menu.");
start = true;
else
//give user option to remove game
System.out.println(teamSchedLL.get(teamSchedLL.indexOf(venueIndex)));
System.out.println("Would you like to remove this game? Y/N");
removeYN = scanner1.nextLine();
if (removeYN == "Y" || removeYN == "y")
teamSchedLL.remove(teamSchedLL.indexOf(venueIndex));
System.out.println("Scheduled game removed.");
System.out.println("\n Returning to main menu. \n");
start = true;
else if (selector == 4)
//search using opponent name
scanner1.nextLine();
System.out.println("Enter the opponent to search for in the format that it was entered:");
opponentIndex = scanner1.nextLine();
if (teamSchedLL.indexOf(opponentIndex) == -1)
System.out.println("No matching opponent found. Returning to main menu.");
start = true;
else
//give user option to remove game
System.out.println(teamSchedLL.get(teamSchedLL.indexOf(opponentIndex)));
System.out.println("Would you like to remove this game? Y/N");
removeYN = scanner1.nextLine();
if (removeYN == "Y" || removeYN == "y")
teamSchedLL.remove(teamSchedLL.indexOf(opponentIndex));
System.out.println("Scheduled game removed.");
System.out.println("\n Returning to main menu. \n");
start = true;
else if (selector == 5)
//display tour info
System.out.println("Tour Schedule:");
System.out.println(teamSchedLL + "\n");
else
System.out.println("Incorrect choice entered. Returning to menu");
System.out.println("");
System.out.println("");
System.out.println("");
and here is the game class:
public class game
private static String gameDate;
private static String gameVenue;
private static String gameTime;
private static double gamePrice;
private static String gameOpponent;
public static String gameString;
//set local variables equal to parameters
public game(String date, String venue, String time, double price, String opponent)
gameDate = date;
gameVenue = venue;
gameTime = time;
gamePrice = price;
gameOpponent = opponent;
//prints out info about the particular game
public String toString()
gameString = "\n --------------------------------------------------------";
gameString += "\n Date: " + gameDate + " | ";
gameString += "Venue: " + gameVenue + " | ";
gameString += "Time: " + gameTime + " | ";
gameString += "Price: " + gamePrice + " | ";
gameString += "Opponent: " + gameOpponent + "\n";
gameString += " --------------------------------------------------------";
return gameString;
}I'm sure the formatting/style and stuff is horrible but if I could just get it to work that would be amazing. Thanks in advance.
Message was edited by:
wdewindI don't understand your first problem.
Your second problem:
for (Iterator it=teamSchedLL.iterator(); it.hasNext(); ) {
game game = (game)it.next();
// do the comparation here, if this is the game want to be searched, then break;
} -
Hi everyone,
I have some problems about Double Linked Lists which I can not overcome. When I execute the following codes, there is an exception occured that is called NullPointer Exception in inser method.
So how can I fix it ??
class DoublyLinkedNode {
// properties
DoublyLinkedNode nextNode;
DoublyLinkedNode previousNode;
int size;
int data;
// constructors
public DoublyLinkedNode(int data,DoublyLinkedNode nextNode, DoublyLinkedNode previousNode){
this.data = data;
this.nextNode = nextNode;
this.previousNode = previousNode;
size = 0;
// methods
public void setNext(DoublyLinkedNode next){
nextNode = next;
public void setPrevious(DoublyLinkedNode pre){
previousNode = pre;
public DoublyLinkedNode getNext(){
return nextNode;
public DoublyLinkedNode getPrevious(){
return previousNode;
public int getData(){
return data;
public void setData(int value){
data = value;
class DoubleLinkedList {
// properties
int size;
DoublyLinkedNode tail;
DoublyLinkedNode head;
String s = "";
// constructors
public DoubleLinkedList(){
head = null;
tail = null;
size = 0;
// methods
public boolean isEmpty(){
if(head == null)
return true;
else
return false;
public DoublyLinkedNode next(){
return head.getNext();
public DoublyLinkedNode previous(){
return head.getPrevious();
public void insert(int data){
head = new DoublyLinkedNode(data, head.getNext(),head.getPrevious());
size++;
public String toString(){
s += head.getData() + "";
head = head.getNext();
if(isEmpty())
return s;
else
return toString();
public static void main(String args[]){
DoubleLinkedList list = new DoubleLinkedList();
list.insert(111);
list.insert(21);
list.insert(311);
list.insert(41);
list.insert(51);
list.insert(16);
list.insert(117);
System.out.println(list.toString());
// for(int a = 0; a < 5; a++){
// list.previous();
}Again, I changed insert method which is now correct I think.
But now, toString cause only appear the last object on the console.
So how can I fix toString method ???
public void insert(int data){
DoublyLinkedNode pointer = head.getPrevious();
DoublyLinkedNode pointer2 = pointer.getNext();
head = new DoublyLinkedNode(data,pointer2, pointer );
} -
Linked List bubbleSort problems
I'm trying to implement a bubbleSort (with a insertionSort and selectionSort) on a linked list, but can't seem to get it working. Any tips on correcting the bubbleSort, and maybe some for the other two? Thanks!!!
public class sortingMethods {
public sortingMethods() {}
public void bubbleSort(LinkedList list) {
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else {
Node current = list.getHead();
Node next = current.getNext();
Node temp;
int counter = 0;
boolean exchangeMade = true;
while(counter < (list.size() - 1) && exchangeMade) {
counter++;
exchangeMade = false;
for(int i = 1; i <= (list.size() - counter); i++) {
if(current.getData() > next.getData()) {
temp = current;
current = next;
next = temp;
exchangeMade = true;
public void selectionSort(LinkedList list) {
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else{}
public void insertionSort(LinkedList list){
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else {
public class LinkedList {
private Node head;
private int count;
public LinkedList() {
head = null;
count = 0;
public LinkedList(LinkedList rhs) { //Copy constructor
head = rhs.head;
count = rhs.count;
public void orderedInsert(int item) { //Inserts the Node in the right position - Ascending
Node back = null;
Node newNode = new Node(item);
Node pointer = head;
boolean found = false;
while(pointer != null && !found) {
if(pointer.getData() > item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
newNode.setNext(pointer);
if(back == null) {
head = newNode;
count++;
else {
back.setNext(newNode);
count++;
public void insert(int item) { //Inserts at front of list
Node newnode = new Node(item);
if(head == null)
head = newnode;
else {
newnode.setNext(head);
head = newnode;
public void orderedRemove(int item) { //Searches and removes selected Node
Node back = null;
boolean found = false;
Node pointer = head;
while(pointer != null && !found) {
if(pointer.getData() == item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
if(found)
if(back == null) {
head = pointer.getNext();
count--;
} else {
back.setNext(pointer.getNext());
count--;
} else
System.out.println("Data not found in list.");
public void remove() { //Removes from front of list
if(head == null)
System.out.println("List is currently empty.");
else {
Node n = head;
head = head.getNext();
n.setNext(null);
count--;
public boolean isEmpty() {
if(head == null)
return true;
else
return false;
public void print() {
Node current = head;
while(current != null) {
System.out.println(current.getData());
current = current.getNext();
public int size() {return count;}
public Node getHead() {return head;}
} //End LinkedList classI'm still having problems! Now the code just seems to go through an endless loop.
public void bubbleSort(LinkedList list) {
if(list.isEmpty())
System.out.println("List is currently empty.");
else if (list.size() == 1)
System.out.println("List is already sorted.");
else {
boolean exchangeMade = true;
int counter = 0;
Node current = list.getHead();
Node next = current.getNext();
Node temp;
while(counter < (list.size() - 1) && exchangeMade) {
counter++;
exchangeMade = false;
for(int i = 1; i <= (list.size() - counter); i++) {
if(current.getData() > next.getData()) {
temp = current;
current.setNext(next);
next.setNext(temp);
exchangeMade = true;
}And here is the rest of my code...
package cs321_assignment1;
public class LinkedList { //Doubly Linked List
private Node head;
private int count;
public LinkedList() {
head = null;
count = 0;
public LinkedList(LinkedList rhs) { //Copy constructor
head = rhs.head;
count = rhs.count;
public void orderedInsert(int item) { //Inserts the Node in the right position - Ascending
Node back = null;
Node newNode = new Node(item);
Node pointer = head;
boolean found = false;
while(pointer != null && !found) {
if(pointer.getData() > item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
newNode.setNext(pointer);
if(back == null) {
head = newNode;
count++;
else {
back.setNext(newNode);
count++;
public void insert(int item) { //Inserts at front of list
Node newnode = new Node(item);
if(head == null)
head = newnode;
else {
newnode.setNext(head);
head = newnode;
count++;
public void orderedRemove(int item) { //Searches and removes selected Node
Node back = null;
boolean found = false;
Node pointer = head;
while(pointer != null && !found) {
if(pointer.getData() == item)
found = true;
else {
back = pointer;
pointer = pointer.getNext();
if(found)
if(back == null) {
head = pointer.getNext();
count--;
} else {
back.setNext(pointer.getNext());
count--;
} else
System.out.println("Data not found in list.");
public void remove() { //Removes from front of list
if(head == null)
System.out.println("List is currently empty.");
else {
Node n = head;
head = head.getNext();
n.setNext(null);
count--;
public boolean isEmpty() {
if(count == 0)
return true;
else
return false;
public void print() {
Node current = head;
while(current != null) {
System.out.println(current.getData());
current = current.getNext();
public int size() {return count;}
public Node getHead() {return head;}
public void setHead(Node n) {head = n;}
} //End LinkedList class
package cs321_assignment1;
public class Node {
private int data;
private Node next;
public Node() {next = null;}
public Node(int d) {
next = null;
data = d;
public int getData() {return data;}
public void setData(int newData) {data = newData;}
public Node getNext() {return next;}
public void setNext(Node newNode) {next = newNode;}
}I can't figure this out, and I really need some help. Hopefully after I solve this, the selection and insertion sorts will be a little simpler. Any help will really be appreciated. -
Faster way to search linked list?
I'm pretty new to programming and I have to write a kind of psuedo implementation of a cache using a linked list (has to be a linked list). The problem is when I'm setting the maximum size of the linked list to a high number (like 2000), it goes incredibly slow. I don't know how I can make this faster.
Here are the 2 main methods I'm using for it:
public void addObject(Object toAdd){
cacheList.addFirst(toAdd);
if(cacheList.size()>=maxAllowedSize){
removeObject(maxAllowedSize-1);
public boolean containsObject(Object toFind){
boolean test=false;
for(int x=0;x<cacheList.size();x++){
if(toFind.equals(cacheList.get(x))){
test=true;
hits++;
removeObject(x);
addObject(toFind);
x=cacheList.size(); //ends for loop
total++;
return test;
}Where maxAllowedSize is a command line argument and removeObject just calls cacheList.remove(index).
For testing, I'm using a text file with something over 1.3 million words and using scanner to read them. Here is the code that calls the two methods:
if(!cache.containsObject(currentWord)){
cache.addObject(currentWord);
}Since containsObject adds the word itself, this calls addObject if the word isn't found (added to the front of the list).
Any help is greatly appreciated.darkambivalence wrote:
Linked list is what was specified in my assignment.
Then to be honest I expect that part of the learning of assignment is to see how a LinkedList is a poor choice for a list that you want to search.
Why will that run poorly? Because what do you think remove is doing? The remove has to search to find the thing you want to remove. So it's doing that search twice. So it will be twice as slow.
There really isn't much you can do to make this faster. LinkedLists are great for many reasons but "random" accessing (for searching for example) is not one of them. I suppose if one really wanted to squeeze out performance you could keep the list sorted. So when inserting insert into the "right" place in the list and then as you search if a value would fall in between two buckets and doesn't exist in your list you can stop there. A doubly linked list would probably help for this implementation.
In the real world though you would either not use a LinkedList at all or a Map depending on the needs. -
Problem with Queue and linked list
Hi... i've got an assignment it start like this.
You are required to write a complete console program in java includin main() to demonstrate the following:
Data Structure: Queue, Priority Queue
Object Involved: Linked-List, PrintJob
Operations Involved:
1. insert
2. remove
3. reset
4. search
Dats all... I've been given this much information... Can any1 try to help me please... How to make a start??? And wat does the print job means???
Can any1 tell me wat am supposed to do...Hi,
Why don't you start your demo like this?
import java.io.IOException;
public class Demo {
public Demo() {
public void startDemo() throws IOException {
do {
System.out.println("String Console Demo ");
System.out.println("\t" + "1. Queue Demo");
System.out.println("\t" + "2. PriorityQueue Demo");
System.out.println("\t" + "3. LinkedList Demo");
System.out.println("\t" + "4. PrintJob Demo");
System.out.println("Please choose one option");
choice = (char) System.in.read();
showDemo(choice);
} while (choice < '1' || choice > '4');
public void showDemo(char ch) {
switch (ch) {
case '1':
System.out.println("You have chosen Queue Demo ");
showOperations();
break;
case '2':
System.out.println("You have chosen Priority Queue Demo ");
showOperations();
break;
case '3':
System.out.println("You have chosen LinkedList Demo ");
showOperations();
break;
case '4':
System.out.println("You have chosen Print Job Demo ");
showOperations();
break;
private void showOperations() {
System.out.println("Please choose any operations ");
System.out.println("\t" + "1. Insert ");
System.out.println("\t" + "2. Remove ");
System.out.println("\t" + "3. Reset ");
System.out.println("\t" + "4. search ");
public static void main(String[] args) throws IOException {
Demo demo = new Demo();
demo.startDemo();
private char choice;
Write a separate classes for the data structures show the initial elements and call the methods based on the operations then show the result.
Thanks -
Problem with removing items from a linked list
Hello,
I have something weird going with my code. Below is the snippet
if (ParserDataList.isEmpty())
try {
Thread.sleep(10)
catch (InterruptedException e) {
else
data = ParserDataList.remove();
ParserDataList is declared as a LinkedList. Occasionally I receive the error on NoSuchElement on the remove. I put a try/catch around the remove and print out the value of ParserDataList.isEmpty which is always false. I am very confused on why if the linked list isn't empty I can't remove a data item. There are no other threads that remove data. Thank you in advance for any assistance on this problem.I am changing it from linked list to blocking queue however I do have a question about what I should use to poll the data? Instead of a remove should I use take which seemed to remove the first element and if there wasn't one wait until there was. I was trying to not have the threads blocked because I do need to stop them when a disconnect is sent from the main thread.
-
Linked lists problem -- help needed
Hello again. I've got yet another problem in my C++ course that stems from my use of a Mac instead of Windows. I'm going to install Parallels so I can get Windows on my MacBook and install Visual Studio this week so that I don't have to deal with these discrepancies anymore, but in the meanwhile, I'm having a problem here that I don't know how to resolve. To be clear, I've spent a lot of time trying to work this out myself, so I'm not just throwing this up here to have you guys do the work for me -- I'm really stuck here, and am coming here as a last resort, so I'll be very, very appreciative for any help that anyone can offer.
In my C++ course, we are on a chapter about linked lists, and the professor has given us a template to make the linked lists work. It comes in three files (a header, a source file, and a main source file). I've made some adjustments -- the original files the professor provided brought up 36 errors and a handful of warnings, but I altered the #include directives and got it down to 2 errors. The problematic part of the code (the part that contains the two errors) is in one of the function definitions, print_list(), in the source file. That function definition is shown below, and I've marked the two statements that have the errors using comments that say exactly what the errors say in my Xcode window under those two statements. If you want to see the entire template, I've pasted the full code from all three files at the bottom of this post, but for now, here is the function definition (in the source file) that contains the part of the code with the errors:
void LinkedList::printlist( )
// good for only a few nodes in a list
if(isEmpty() == 1)
cout << "No nodes to display" << endl;
return;
for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
{ cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
{ cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
As you can see, the problem is with the two statements that contain the 'setw' function. Can anyone help me figure out how to get this template working and get by these two errors? I don't know enough about linked lists to know what I can and can't mess with here to get it working. The professor recommended that I try using 'printf' instead of 'cout' for those two statements, but I don't know how to achieve the same effect (how to do whatever 'setw' does) using 'printf'. Can anyone please help me get this template working? Thank you very, very much.
For reference, here is the full code from all three files that make up the template:
linkedlist.h (header file):
#ifndef LINKED_LINKED_H
#define LINKED_LINKED_H
struct NODE
string name;
int test_grade;
NODE * link;
class Linked_List
public:
Linked_List();
void insert(string n, int score);
void remove(string target);
void print_list();
private:
bool isEmpty();
NODE *FRONT_ptr, *REAR_ptr, *CURSOR, *INSERT, *PREVIOUS_ptr;
#endif
linkedlist.cpp (source file):
#include <iostream>
using namespace std;
#include "linkedlist.h"
LinkedList::LinkedList()
FRONT_ptr = NULL;
REAR_ptr = NULL;
PREVIOUS_ptr = NULL;
CURSOR = NULL;
void Linked_List::insert(string n, int score)
INSERT = new NODE;
if(isEmpty()) // first item in List
// collect information into INSERT NODE
INSERT-> name = n;
// must use strcpy to assign strings
INSERT -> test_grade = score;
INSERT -> link = NULL;
FRONT_ptr = INSERT;
REAR_ptr = INSERT;
else // else what?? When would this happen??
// collect information into INSERT NODE
INSERT-> name = n; // must use strcpy to assign strings
INSERT -> test_grade = score;
REAR_ptr -> link = INSERT;
INSERT -> link = NULL;
REAR_ptr = INSERT;
void LinkedList::printlist( )
// good for only a few nodes in a list
if(isEmpty() == 1)
cout << "No nodes to display" << endl;
return;
for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
{ cout << setw(8) << CURSOR->name; } cout << endl; // error: 'setw' was not declared in this scope
for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
{ cout << setw(8) << CURSOR->test_grade; } cout << endl; // error: 'setw' was not declared in this scope
void Linked_List::remove(string target)
// 3 possible places that NODES can be removed from in the Linked List
// FRONT
// MIDDLE
// REAR
// all 3 condition need to be covered and coded
// use Trasversing to find TARGET
PREVIOUS_ptr = NULL;
for(CURSOR = FRONT_ptr; CURSOR; CURSOR = CURSOR-> link)
if(CURSOR->name == target) // match
{ break; } // function will still continue, CURSOR will
// mark NODE to be removed
else
{ PREVIOUS_ptr = CURSOR; } // PREVIOUS marks what NODE CURSOR is marking
// JUST before CURSOR is about to move to the next NODE
if(CURSOR == NULL) // never found a match
{ return; }
else
// check each condition FRONT, REAR and MIDDLE
if(CURSOR == FRONT_ptr)
// TARGET node was the first in the list
FRONT_ptr = FRONT_ptr -> link; // moves FRONT_ptr up one node
delete CURSOR; // deletes and return NODE back to free memory!!!
return;
}// why no need for PREVIOUS??
else if (CURSOR == REAR_ptr) // TARGET node was the last in the list
{ // will need PREVIOUS for this one
PREVIOUS_ptr -> link = NULL; // since this node will become the last in the list
REAR_ptr = PREVIOUS_ptr; // = REAR_ptr; // moves REAR_ptr into correct position in list
delete CURSOR; // deletes and return NODE back to free memory!!!
return;
else // TARGET node was the middle of the list
{ // will need PREVIOUS also for this one
PREVIOUS_ptr -> link = CURSOR-> link; // moves PREV nodes' link to point where CURSOR nodes' points
delete CURSOR; // deletes and return NODE back to free memory!!!
return;
bool Linked_List::isEmpty()
if ((FRONT_ptr == NULL) && (REAR_ptr == NULL))
{ return true; }
else
{ return false;}
llmain.cpp (main source file):
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
#include "linkedlist.h"
int main()
Linked_List one;
one.insert("Angela", 261);
one.insert("Jack", 20);
one.insert("Peter", 120);
one.insert("Chris", 270);
one.print_list();
one.remove("Jack");
one.print_list();
one.remove("Angela");
one.print_list();
one.remove("Chris");
one.print_list();
return 0;setw is the equivalent of the field width value in printf. In your code, the printf version would look like:
printf("%8s", CURSOR->name.c_str());
I much prefer printf over any I/O formatting in C++. See the printf man page for more information. I recommend using Bwana: http://www.bruji.com/bwana/
I do think it is a good idea to verify your code on the platform it will be tested against. That means Visual Studio. However, you don't want to use Visual Studio. As you have found out, it gets people into too many bad habits. Linux is much the same way. Both development platforms are designed to build anything, whether or not it is syntactically correct. Both GNU and Microsoft have a long history of changing the language standards just to suit themselves.
I don't know what level you are in the class, but I have a few tips for you. I'll phrase them so that they answers are a good exercise for the student
* Look into const-correctness.
* You don't need to compare a bool to 1. You can just use bool. Plus, any integer or pointer type has an implicit cast to bool.
* Don't reuse your CURSOR pointer as a temporary index. Create a new pointer inside the for loop.
* In C++, a struct is the same thing as a class, with all of its members public by default. You can create constructors and member functions in a struct.
* Optimize your function arguments. Pass by const reference instead of by copy. You will need to use pass by copy at a later date, but don't worry about that now.
* Look into initializer lists.
* In C++ NULL and 0 are always the same.
* Return the result of an expression instead of true or false. Technically this isn't officially Return Value Optimization, but it is a good habit.
Of course, get it running first, then make it fancy. -
Linked list- error problem.... HELP!!!
Just got to the point that i'm better at drinking java than programing java....
how ever... I have done person register with Linked list. There are like 4 options:
1. New post
2. search
3. search and change
4. remove post
U can enter your name, adress and personal code number while making a new post, but when I've removed it ( l.list.remove(p);)and then search for it I get the error message "Exception in thread "main"....bla bla..". Why? and how do I get around this prob? PLEASE HELP ME!! gotta hand this in tonight!
Thank U!!
//PhilPhil,
LinkedList itself works as advertised (1.3.1). For example:
LL = LinkedList()
LL.add("apple")
LL.add("battle")
LL.add("cattle")
// printing LL yields all 3
LL.remove("battle")
// printing LL yields apple, cattle
You may need to post for responders to get a better idea. If posting code please enclose in blocks so it's formatted properly.
--A -
Search in Double link list in java
Can any body give me the code implementation for searching an element in double link list in java as soon as possible...
Can any body give me the code implementation for
searching an element in double link list in java as
soon as possible...Psuedo code...
current = head of list
found = null
while(current is not null)
if doesItMatch(current, target)
break
current = current->next
if (current is null) Out("no match")
else Out("found it") -
Problem with Help Link in search result screen of PCUI
Hi,
I am trying to access the pcui applications that came out of box with crm using BAB,everthing is working fine but got a problem with "Help" link in top right (beside personalize link) the search result area of all the PCUI screens.
when i click on that i get "page cannot be displayed" error, seems that it is pointing to some wrong URL, where should i change the url to point to our company's help site for that link..
clicking on the properties of that link shows that it is pointing to
javascript:CATshowF1(%20'/sap/bc/bsp/sap/crm_bsp_f1_help/f1help.do?doctype=kw&loio=70B4ED8E03595645A6ABA33B4576BB57&class=IWB_EXTHLP&language=E' );
Please help me in this regard.
Thank youMy response help resolve Kodru's Message which he also posted in EP Implementation Forum. He resolved it by changing the variant noted below.
The link http://help.sap.com/saphelp_crm40/helpdata/EN/70/B4ED8E03595645A6ABA33B4576BB57/content.htm should display Activity Info.
First I would check if the crm_bsp_f1_help service has been activated in SICF.
Secondly I would check the settings in the IMG -> SAP WAS -> Know. Mgt. -> Settings in App. Sys. -> Usage of Help Type "Dynamic Help". The Tab PlainHtmlHttp should have a variant called CRM_HELP, Server Name (help.sap.com) and path. -
i have make a database with linked list for a School student counselor.
The to be store is
student name, ID, Counseling Date, Progress
In there there will be record for a student and the Date and progress has to be stored for 4-weeks as the counseling is on weekly basis. These data items will be multivalued(what u say in Databases) how i can store this repetitive data in linked list for one student.By capsulating the data in objects and adding the objects to a linked list.
-
I have one link list class. Each record holds only one data.
Now I am going to modify it. Each record holds two real numbers.
how to do it?
Thanks
class ListNode
// package access members; List can access these directly
Object data;
ListNode nextNode;
// constructor creates a ListNode that refers to object
ListNode( Object object )
this( object, null );
} // end ListNode one-argument constructor
// constructor creates ListNode that refers to
// Object and to next ListNode
ListNode( Object object, ListNode node )
data = object;
nextNode = node;
} // end ListNode two-argument constructor
// return reference to data in node
Object getObject()
return data; // return Object in this node
} // end method getObject
// return reference to next node in list
ListNode getNext()
return nextNode; // get next node
} // end method getNext
} // end class ListNode
// class List definition
public class List
private ListNode firstNode;
private ListNode lastNode;
private String name; // string like "list" used in printing
// constructor creates empty List with "list" as the name
public List()
this( "list" );
} // end List no-argument constructor
// constructor creates an empty List with a name
public List( String listName )
name = listName;
firstNode = lastNode = null;
} // end List one-argument constructor
// insert Object at front of List
public void insertAtFront( Object insertItem )
if ( isEmpty() ) // firstNode and lastNode refer to same object
firstNode = lastNode = new ListNode( insertItem );
else // firstNode refers to new node
firstNode = new ListNode( insertItem, firstNode );
} // end method insertAtFront
public static void main( String args[])
List list1 = new List();
int array1[] = { 160, 591, 114, 229, 230, 270, 128, 1657, 624, 1503 };
//insert numbers in list
for (int c1 = 0; c1 < array1.length; c1++ )
list1.insertAtFront(array1[ c1 ]);
...ok, there we go.
I modified a little.
I added a class.
public class data
private double x;
private double y;
public data(double x,double y)
x=this.x;
y=this.y;
}in main program
public static void main( String args[] )
List list = new List(); // create the List container
data x1 =new data(9,-9);
list.insertAtFront( x1 );
list.print();
data x2 =new data(8,-8);
list.insertAtFront( x2 );
list.print();
data x3 =new data(7,-7);
list.insertAtBack( x3 );
list.print();
data x4 =new data(6,-6);
list.insertAtBack( x4 );
list.print();
...Do I need change print method, some errors occuried.
public void print()
if ( isEmpty() )
System.out.printf( "Empty %s\n", name );
return;
} // end if
System.out.printf( "The %s is: ", name );
ListNode current = firstNode;
// while not at end of list, output current node's data
while ( current != null )
System.out.printf( "%s ", current.data );
current = current.nextNode;
} // end while
System.out.println( "\n" );
} // end method print
} // end class List -
Link Lists Problem!!!
I have array of employees that i am inserting into Linked List. Everything is working fine except my forward and backward displays are swapped.
Forward should display Emp in ascending order and Backward should display the other way around. Mine are swapped? What am i missing?
public void insertFirst(Emp e)
Link newLink = new Link(st);
if(isEmpty())
last = newLink;
else
first.previous = newLink;
newLink.next = first;
first = newLink;
public void displayForward()
System.out.print("\n\n");
System.out.print("Doubly-Linked List of Employees Using Forward Pointers\n\n");
Link current = first;
while(current != null)
current.displayLink();
current = current.next;
System.out.println(" ");
public void displayBackward()
System.out.print("Doubly-Linked List of Employees Using Backward Pointers\n\n");
Link current = last;
while(current != null)
current.displayLink();
current = current.previous;
System.out.println(" ");
}What are you using to add items to the list? Not this insertFirst method that inserts at the beginning, right? You are instead using a different method that inserts at the end of the list, correct?
Maybe you are looking for
-
How Can I Get My Photoshop Files to Display as Thumbnails
I received over 200 pictures that are in a PSD format and I need to be able to view these files through a Windows Explorer window- not through Bridge. I have CS3 and I don't like Bridge. It's really slow (my computer is made for heavy graphic work) a
-
Java Error in RFC Lookup in XSLT Mapping usinf Java helper class
Hi All, I am doing RFC Lookup in XSLT Mapping using Java Helper class. The Lookup works fine when called one RFC at a time However my requirement is I want to do 2 Lookups. Both Lookups works when done individually however when I call both lookups in
-
After much frustration, got CS2 installed to replace my now-unsupported CS1. Went to open Adobe Photoshop and got your Adobe Photoshop user name, organization name or serial number is missing or invalid.
-
How to save an "Object" in a selected file ?
Hi, I would like to save an object with for example a PlanarImage object type in a selected file from JFileChooser Do you know how to do it ? I tried this but it didn't work : File fChoosen = chooser.getSelectedFile(); ObjectOutputStream os = new Obj
-
J2ee tutorial. "ant create-tables" problem
I am following Java ee 5 tutorial. In one of its sections it asks me to populate the db by following the below instructions: 1. In a terminal window, go to the books directory or any one of the bookstore1 through bookstore6 example directories. 2. St