下面是我的c语言双向链表,next指针遍历没问题,last指针遍历就出问题了,求解哪里搞错了

//地方不太够,其他函数和主函数都没写,请大神费心看看创建还是遍历有错误
struct NODE
{
int data;
struct NODE *next;
struct NODE *last;
};
typedef struct NODE Node;

void create_list(Node *head)
{
Node *tail = head;
Node *pnew = NULL;
int data;

while(1)
{
printf("Input a data(<= 0 to end input):");
scanf("%d", &data);
if(data <= 0)
{
break;
}

pnew = (Node *)malloc(sizeof(Node));
assert(pnew);

pnew->data = data;

pnew->next = tail->next;
tail->next = pnew;

pnew->last = tail;

tail = tail->next;
}
}

void output_list(Node *head)
{
if(is_empty(head))
{
fprintf(stderr, "Output List: Empty!\n");
return;
}

Node *tmp = head->next;
puts("——output——————————————");
while(tmp)
{
printf("%4d", tmp->data);
tmp = tmp->next;
}
puts("\n");

tmp = tmp->last;
puts("——reverse output————————————");
while(tmp)
{
printf("%4d", tmp->data);
tmp = tmp->last;
}
puts("");

}

#include <stdio.h>
#include <stdlib.h>

struct NODE {
int data;
struct NODE *next;
struct NODE *front;
};

typedef struct NODE Node;

void create_list(Node *head) {
Node *p = head;
int data;
while(1) {
printf("Input a data(<= 0 to end input):");
scanf("%d", &data);
if(data <= 0) break;

p->next = (Node *)malloc(sizeof(Node));
// assert(p->next);

p->next->data = data;
p->next->front = p;

p = p->next;
}
p->next = head;  // 循环双向
head->front = p;
}

void output_list(Node *head) {
// if(is_empty(head)) {
// fprintf(stderr, "Output List: Empty!\n");
// return;
// }

Node *tmp = head->next;
puts("** output **");
while(tmp != head) {
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("\n");

tmp = tmp->front;
puts("** reverse output **");
while(tmp != head) {
printf("%d ", tmp->data);
tmp = tmp->front;
}
puts("");
}

int main() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
head->next = NULL;
head->data = 0;
create_list(head);
output_list(head);
return 0;
}

温馨提示:答案为网友推荐,仅供参考
相似回答