the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > in your code, insertnode function creates a new node, but did not set a new node data, every time to insert a new node, The data field of the new node is random, so the program will always output an infinite number of random numbers. Also, the list insertion logic in the insertnode function is problematic.
Here is the modified code:
#include
#include
typedef struct node
{
int data;
struct node* next; //指向下一个节点的指针
}NODE;
NODE* creatNode(int data)
{
NODE* newnode = (NODE*)malloc(sizeof(NODE));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
NODE* creatList() //创建新结点或说创建链表
{
NODE* head = creatNode(0);
return head;
}
void insertNode(NODE* headnode, int data) //插入结点,参数:所要插入的链表,所要插入的结点的数据
{
NODE* newnode = creatNode(data); //创建插入的结点
newnode->next = headnode->next; //让newnode指向headnode的下一个结点
headnode->next = newnode; //headnode指向newnode
}
void printList(NODE * headnode) //打印链表
{
NODE * pmove= headnode->next;
while (pmove)
{
printf("%d ", pmove->data);
pmove = pmove->next;
}
printf("\n");
}
int main()
{
NODE* head = creatList();
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
printList(head);
return 0;
}
The main contents of
modification include:
- changed the data domain word of the node from date to data.
- Modifies the function creatNode that creates the node and sets the data field of the node.
- modified the function creatList that creates the linked list to make the data field of the header node 0, making the data field of the header node meaningless.
- modifies the insertNode function by setting the next pointer to the new node, ensuring that the inserted node is placed first in the list.
- modified the function printList, which prints a linked list, to correctly print the node's data field instead of printing the address.
This will print the elements of the linked list correctly.