我是C语言中链接列表的新手。我创建了一个代码,您可以在其中将成员添加到列表的开头,将成员添加到列表的末尾并打印列表。该代码读取从用户a,b或p输入的字符。 a将添加到列表的开头。 b到最后。 p用于打印列表。但是由于某些原因,当我添加时,列表的开头或结尾处都会出现一个不需要的0。有什么想法吗?
输入:
>a
>6
>p
输出:
>The list: 6 0
所需的输出应该是
>The list: 6
代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node * next;
} node_t;
void displayList(node_t * head);
void push(node_t * head, int number);
void pushfront(node_t ** head, int val);
int main(int argc, char const *argv[])
{
int num;
char c;
node_t * head = NULL;
head = malloc(sizeof(node_t));
if (head == NULL)
{
return 1;
}
while (c != 'q')
{
scanf("%c", &c);
if (c =='b')
{
scanf("%d", &num);
push(head, num);
}
if (c=='a')
{
scanf("%d", &num);
pushfront(&head,num);
}
if (c=='p')
{
printf("The list: ");
displayList(head);
}
}
return 0;
}
void displayList(node_t * head)
{
node_t * p = head;
while(p != NULL)
{
printf("%d ", p->val);
p=p->next;
}
}
//adding item to the end of the list
void push(node_t * head, int number)
{
node_t * current = head;
while (current->next != NULL) {
current = current->next;
}
/* now we can add a new variable */
current->next = malloc(sizeof(node_t));
current->next->val = number;
current->next->next = NULL;
}
//add item to the beginning of the list
void pushfront(node_t ** head, int val)
{
node_t * new_node;
new_node = malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}