#include <stdio.h>
#include <stdlib.h>
#define len 4
typedef struct head_node{
int data;
struct head_node * next;
struct head_node * head;
}headnode;//定义头节点,拥有两个指针,就是头指针和下一个指针
typedef struct body_node{
int data;
int flag;
struct body_node * next;
}bodynode;//定义身体节点,拥有定位标志和数据域和下一指针
bodynode * linedlistbody_init(void){
bodynode * node = (bodynode *)malloc(sizeof (bodynode));
if(node == NULL){
return NULL;
}
else{
node ->data = 0;
node ->flag = 0;
node ->next = NULL;
return node;
}
}//初始化身体节点,返回身体节点的地址
headnode * linedlist_init(void){
headnode * node = (headnode *)malloc(sizeof (headnode));
if(node == NULL){
return NULL;
}
else{
node ->data = 0;
node ->next = NULL;
node ->head = node;
return node;
}
}//初始化头节点,返回头节点的地址
void linedlist(bodynode *S,int data){
if (S ->flag >= len){
printf("超过了限制长度!\n");
}//当身体节点超过限制时打印信息
else if(S ->flag == len -1){
S ->data = data;
S ->next = NULL;
S ->flag = S ->flag +1;
printf("node%d ->data = %d\n",S ->flag,S ->data);
}
else{
bodynode * node = (bodynode *)malloc(sizeof (bodynode));
S ->data = data;
S ->next = node;
S ->flag = S ->flag +1;
printf("node%d ->data = %d\n",S ->flag,S ->data);
}//当没有到达限制的时候我们就会开辟一个又一个的节点来存储数据
}
void printlinedlist(headnode *S){
headnode *node = S;
while(node ->next !=NULL){
node = node ->next;
printf("%d\n",node ->data);
}
}
int main(void) {
headnode * head = linedlist_init();
if (head != NULL){
printf("开辟成功!\n");
} else{
printf("开辟失败!\n");
}
bodynode * body = linedlistbody_init();
if (body != NULL){
printf("开辟成功!\n");
} else{
printf("开辟失败!\n");
}
head ->next = body;
linedlist(body,4);
linedlist(body,3);
linedlist(body,2);
linedlist(body,1);
printlinedlist(head);
return 0;
}
我发现我将数据节点的链表头地址赋值给遍历函数printlinedlist(headnode *S)的时候,在经历了链表的数据连接后我的头指针都会移到链表最后一个节点,导致我的遍历函数只能打印出最后一个节点的数据,我应该怎样操作才能保存住我的头指针,然后能让我遍历的时候从头遍历到尾,或者我如何让我的指针从后面移动回来,请大家赐教!
开一个新的指针专门用来保存头指针不就好了