-
Linked List
This is a short program for a linked list. I am not sure if I got the process correctly. Any help is much appreciated.
Code:
#pragma once
class LinkedList
{
public:
LinkedList(void);
~LinkedList(void);
void add(char c){
Node temp=new Node;
Node temp2=new Node;
temp->token=c;
if(strPtr==NULL){
strPtr=temp;
strPtr->link=NULL;
}
else{
for(temp=strPtr; temp->link!=NULL; temp=temp->link){}
temp2->token=c;
temp->link=temp2;
temp2->link=NULL;
}
}
void remove(Node node){
Node temp;
temp=strPtr;
if(temp==node){
strPtr=NULL;
delete temp;
}
else if (strPtr!=NULL){
for(temp=strPtr; temp->link!=node; temp=temp->link){}
temp=temp->link->link;
delete temp->link;
}
}
private:
struct Node{
char * token;
Node * link;
}
Node * stPtr=NULL;
};
-
You mean aside from the obvious errors, like typos, illegal syntax and type mismatches, which the compiler would catch if you only tried to compile the code before posting?
Well, aside from that, it's completely wrong. Your interface is unusable. Your insertion code has small logical errors, and uses a single-linked list unidiomatically. Your removal code is broken.
Really, there's not much there is right about this code.
-
i fixed it
well, let's see...
i dont have things to do so i fix it:
Code:
#include <iostream>
class LinkedList
{
public:
struct Node{
char * token;
Node * link;
};
LinkedList(void){
strPtr = NULL;
}
~LinkedList(void){}
void add(char *c){
Node *temp=new Node;
Node *temp2=new Node;
temp->token=c;
if(strPtr==NULL){
strPtr=temp;
strPtr->link=NULL;
}
else{
for(temp=strPtr; temp->link!=NULL; temp=temp->link){}
temp2->token=c;
temp->link=temp2;
temp2->link=NULL;
}
}
Node *getNode(char *c){
Node *temp;
for(temp=strPtr; temp->link!=NULL; temp=temp->link){
if (strcmp(temp->token, c) == 0)
return temp;
}
}
void remove(Node *node){
Node *temp;
Node *temp2;
temp=strPtr;
if(temp == node){
strPtr=temp->link;
delete temp;
}
else if (strPtr!=NULL){
for(temp=strPtr; temp->link!=node; temp=temp->link){}
temp2 = temp->link;
temp->link=temp->link->link;
delete temp2;
}
}
private:
Node * strPtr;
};
int main()
{
LinkedList ll;
ll.add("how");
ll.add("are");
ll.add("you");
LinkedList::Node *to_be_deleted = ll.getNode("you");
ll.remove(to_be_deleted);
}
it works, at least in my vc++...
this is my suggestion:
* try compile your code first...bunch of error you know...
* how do you gonna remove linked list...?what parameter are you gonna send...? its node...? how do you know the node? it's a pointer? so i add new function: getNode(char *c)
* best of all i think you know already about linked list... i can see your logic is right...
i have tried it, but make sure again, try delete head, middle, and the tail of the linked list. because, you know, its different in condition...
cheers ;)