如何使用链表输出字符?


#include <iostream>
using namespace std;
class FloatList
{
private:
// Declare a structure for the list
struct ListNode
{
float value;
struct ListNode *next;
}; 
ListNode *head;   // List head pointer

public:
FloatList();  // Constructor
void appendNode(float num);
};
FloatList::FloatList()  
{ 
head = NULL; 
}
void FloatList::appendNode(float num)
{
ListNode *newNode, *nodePtr;
// Allocate a new node & store num
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;

// If there are no nodes in the list
// make newNode the first node
if (!head)
head = newNode;
else    // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next; 
// Insert newNode as the last node
nodePtr->next = newNode;
} cout << num << " has been APPENDED!" << endl;
}

int main()
{
FloatList list;
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
}

说明:将上述带有追加操作的链表ADT转换为链表模板,使其能够处理不同数据类型的数据。程序完成后,将主程序更改为以下内容:

int main()
{
FloatList list;
list.appendNode('a');
list.appendNode('b');
list.appendNode('c');
cout <<  "Successful Append!" << endl;
}

我可以打印浮点数(2.5)(7.9)和(12.6),但是我不能编辑程序,使其能够打印'a', 'b'和'c'

这是预期的输出:

a has been APPENDED!
b has been APPENDED!
c has been APPENDED!
Successful Append!

如果您想使它适用于字符串类型或char类型,则必须将链表转换为模板化类。看看你对node的定义:

struct ListNode
{
float value;
struct ListNode *next;
}; 

你把float定义为value,那么你怎么期望它能保存char类型呢?我改变了你的linkedlist,所以现在它可以接受任何你想要的类型:

#include <iostream>
using namespace std;
template <typename T>
class FloatList
{
private:
// Declare a structure for the list
struct ListNode
{
T value;
struct ListNode* next;
};
ListNode* head;   // List head pointer
public:
FloatList()
{
head = NULL;
}// Constructor
void appendNode(T num)
{
ListNode* newNode, * nodePtr;
// Allocate a new node & store num
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;
// If there are no nodes in the list
// make newNode the first node
if (!head)
head = newNode;
else    // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node
nodePtr->next = newNode;
} cout << num << " has been APPENDED!" << endl;
}
};

int main()
{
FloatList<float> list;
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
FloatList<char> char_list;
char_list.appendNode('c');
char_list.appendNode('d');
char_list.appendNode('e');
}

由于您的列表现在是模板化的类,您必须指定模板化的类型:

FloatList<float> list;

解决方案真的很好很简单,你所要做的就是在你的类定义中改变两件事:A)告诉编译器这个类是模板化的

template <typename T>
class FloatList

b)将所有浮点数交换为T(我们想要的类型):

float value;
T value;
void appendNode(float num) 
void appendNode(T num)

最新更新