24. Create a struct that holds an int and a pointer to another
instance of the same struct. Write a function that takes
the address of one of these structs and an int indicating
the length of the list you want created. This function will
make a whole chain of these structs (a linked list), starting
from the argument (the head of the list), with each one
pointing to the next. Make the new structs using new,
and put the count (which object number this is) in the int.
In the last struct in the list, put a zero value in the pointer
to indicate that it’s the end. Write a second function that
takes the head of your list and moves through to the end,
printing out both the pointer value and the int value for
each one.
*/
#ifndef SOLUTION24_H
#define SOLUTION24_H
struct Link {
int count;
Link* next;
};
void Makelist (Link* lnk, int length);
void Headmove (Link* lnk);
#endif //SOLUTION24_H
#include"solution24.h"
using namespace std;
void Makelist (Link* lnk, int length) {
static int i = 1;
if (length == 1) {
lnk->next = 0;
lnk->count = i;
return;
}
lnk->next = new Link;
lnk->count = i;
i++;
Makelist (lnk->next, length - 1);
}
void Headmove (Link* lnk) {
cout << lnk->count << endl;
cout << lnk->next << endl;
if (lnk->next == 0)
return;
Headmove (lnk->next);
}
#include"solution24.h"
using namespace std;
int main() {
Link Test;
Makelist (&Test, 10);
Headmove (&Test);
}
本文介绍了一个使用C++实现的简单链表创建方法及如何遍历该链表并打印每个节点的数据。通过递归函数创建指定长度的链表,并在最后一个节点设置空指针标志。随后使用另一个函数从头节点开始遍历整个链表,打印每个节点的计数值及其指向下一个节点的指针值。
480

被折叠的 条评论
为什么被折叠?



