实现在链表头插入结点

直接上代码,图书馆要关门了。。。

 1 //inserting a node at beginning
 2 #include<cstdio>
 3 #include<cstdlib>
 4 
 5 typedef struct node {
 6     int data;
 7     struct node* next;
 8 }Node;
 9 
10 Node* head;//头指针为全局变量 
11 
12 void Insert(int x)
13 {
14     //temp指针变量是在stack中定义,指向的动态分配的内存是在堆中 
15     Node* temp = (Node*)malloc(sizeof(struct node));//在堆栈中分配空间,返回该空间的首地址 
16     temp->data = x;
17     temp->next = head;
18     head = temp;
19 }
20 
21 void Print()
22 {
23     Node* tmp = head;//把头指针赋给临时指针,目的是防止链表的头指针的丢失 
24     printf("List is:");
25     while (tmp != NULL)//注意这种错误:tmp -> next != NULL,找这个bug找了半天 
26     {
27         printf("%d ", tmp->data);
28         tmp = tmp->next;
29     }
30     printf("\n");
31 }
32 
33 int main() {
34     head = NULL;//空链表 
35     int i, n, x;
36     printf("How many number do you want to insert?\n");
37     scanf("%d", &n);
38     for (i = 0; i < n; i++) {
39         printf("Enter the number:\n");
40         scanf("%d",&x);
41         Insert(x);
42         Print();
43     }
44     return 0;
45 }

用c++实现的改天再发!

posted @ 2021-09-23 21:40  越菜越自信  阅读(192)  评论(0)    收藏  举报