我试图在我的循环单向链表中将两端连接在一起。 在文件名 file.txt 中,包含 ABCDEFGHIJKLMNOPQRSTUVWXYZ 作为文本,我能够 分别打印出头部和尾部 A 和 Z。但是,我希望 Z 指向 A 但是我的输出是 A 的地址(见下文)。我在 addNode() 中做错了什么?
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream> // For file input
#include <cassert> // for assertions
using namespace std;
FILE *filename = fopen("file.txt", "r"); // Try to open file
struct Node
{
char data;
Node* next;
} ;
void addNode( Node * &head, Node * &tail, char input)
{
Node *pTemp = new Node;
pTemp->data = input;
if( head == NULL)
{
head=pTemp;
tail=pTemp;
tail->next = head;
}
else
{
tail->next = pTemp;
pTemp->next=head;
}
tail=pTemp;
}//end addNode()
int main()
{
assert(filename);
Node *head=NULL;
Node *tail=NULL;
char c =' ';
int i=0;
while( fscanf(filename,"%c", &c) != EOF)
addNode( head,tail, c);
cout<<endl;
cout<<"\nHead element is "<<head->data<<endl;
cout<<"Tail element is "<<tail->data<<endl;
cout<<"After tail '"<<tail->data<<"' is : "<< tail->next<<endl;
}
当前输出为:
Head element is A
Tail element is Z
After tail 'Z' is : 0x371168
期望的输出是:
Head element is A
Tail element is Z
After tail 'Z' is : A
最佳答案
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream> // For file input
#include <cassert> // for assertions
using namespace std;
FILE *filename = fopen("file.txt", "r"); // Try to open file
struct Node
{
char data;
Node* next;
} ;
void addNode( Node * &head, Node * &tail, char input)
{
Node *pTemp = new Node;
pTemp->data = input;
if( head == NULL)
{
head=tail =pTemp;
tail->next=pTemp;
}
else
{
pTemp->next = tail->next;
tail->next=pTemp;
tail = pTemp;
}
}//end addNode()
int main()
{
assert(filename);
Node *head=NULL;
Node *tail=NULL;
char c =' ';
int i=0;
while( fscanf(filename,"%c", &c) != EOF)
addNode( head,tail, c);
cout<<endl;
cout<<"\nHead element is "<<head->data<<endl;
cout<<"Tail element is "<<tail->data<<endl;
cout<<"After tail '"<<tail->data<<"' is : "<< tail->next->data<<endl;
}
试试这个。
我已经进一步改进并从您的 addNode 中删除了所需的代码。
你想设置“tail->next = pTemp;”的原因是因为 pTemp 是一个新内存,并且因为您正在制作链接列表,所以您希望前一个节点(下一个)指针指向新内存。因此它创建了一个链接列表。
这样你不仅可以遍历第一个和最后一个元素。您可以遍历整个链接列表。
如果您错过了这条语句,那么您将无法遍历。前一个节点的下一个变量不会与下一个连接。
例子:
Node A
[A | pointer to self] <- head and tail
Node B
[A | pointer to B ] <-head
[B | pointer to A ] <-tail
Node C
[A | pointer to B ] <-head
[B | pointer to C ]
[C | pointer to A ] <-tail
Node D
[A | pointer to B ] <-head
[B | pointer to C ]
[C | pointer to D ]
[C | pointer to A ] <-tail
关于c++ - tail->下一个打印地址代替数据循环链表c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25830668/