link list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Bob Zambanini - Monday, March 14, 2011 - lab5_2.cpp
\

#include <iostream>

using namespace std;

const short unsigned int NUMVALS = 10;

struct ListNode {
	double Celement;
	ListNode* next;
};
ListNode* alpha = NULL;

bool insertNode(char element);
void displayList(void);


int main(void)
{
	 
	char temp[30];
	cout<<"input something";
	cin>>temp;
	char* name = temp;  


	short unsigned int i;
	for(i=0; i<NUMVALS; i++) { // insert the array element into the linked list
		if(insertNode(temp[i])) {
			cout << "Error in function insertNode!\n";
			cout << "Program will halt!\n";
			exit(1);
		}
	}

	displayList();

}

bool insertNode(char element)
// This function inserts a node into our linked list.
{
	ListNode* newNode;
	ListNode* nodePtr = alpha;
	ListNode* prevNodePtr = NULL;
	
	newNode = new ListNode;
	if(newNode == NULL) {
		cout << "Error allocating memory for new list member!\n";
		return 1;
	}

	newNode->Celement = element;
	newNode->next = NULL;

	if(alpha==NULL) { // check if list is currently empty
		cout << "List is currently empty - " << newNode->Celement;
		cout << " is part of the list's first node!\n";
		alpha = newNode;
	}
	else {
		while(nodePtr != NULL) {
			prevNodePtr = nodePtr;  // advance prevNodePtr up to nodePtr
			nodePtr = nodePtr->next;  // advance nodePtr by 1 node
		}
		if(prevNodePtr == NULL) {// at beginning of list
			newNode->next = alpha;
			alpha = newNode;
		}
		
	}

	return 0;
}

void displayList(void)
// This function displays our linked list!
{
	ListNode* nodePtr = alpha;
	

	if(alpha == NULL) {
		cout << "List is currently empty!\n";
	}
	else {
		while (nodePtr != NULL) {
			cout << nodePtr->Celement << endl;
			nodePtr = nodePtr->next;
		}
	}
}


As you can see i am trying to store each char element in a link list.(by doing that i can print it backwards) however the problem is no matter what i type (e.g i type keith) it will said the list is empty program will halt. my second problem is if i sucessfully fix the first problem (which is storing each char element in each link list) how to display it backwards>?
Last edited on
I haven't looked at linked lists yet, but by the looks of that, you're trying to store a char into a double.

Look on your other post, I posted a way to write it backwards.
Topic archived. No new replies allowed.