链表的创建,结点的插入,以及链表的打印删除等,这可以相当于一个模板记下来!
喜欢的小伙伴可以点个♥,蟹蟹~
加油!
永远不会倒,我心中的不死鸟!
#include <stdio.h>
#include<malloc.h>
struct Node {
int val;
struct Node* next;
};
//创建
struct Node* createNode(int val) {
struct Node* p = NULL;
p = (struct Node*)malloc(sizeof(struct Node));
if (p == NULL) {
printf("创建失败!\n");
return NULL;
}
p->val = val; //f赋值
p->next = NULL;
return p;
}
//插入
void insertNode(struct Node* q, int val) {
struct Node *p;
p = (struct Node*)malloc(sizeof(struct Node));
if (p == NULL) {
printf("创建失败!\n");
return ;
}
p->val=val;
p->next=q->next;
q->next=p;
}
//打印
void printfNode(struct Node* p)
{
struct Node* head =p;
while(head->next!=NULL)
{
printf("%d ",head->val);
head=head->next;
}
}
int main() {
int n, i;
scanf("%d", &n);
int *arr=(int *)malloc(sizeof(int)*n);
struct Node* head = createNode(0); //创建链表
struct Node* p = head;
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
head->val=arr[0];
for (i = 1; i <=n; i++) {
insertNode(p, arr[i]);
p = p->next;
}
printfNode(head);
free(p);
return 0;
}
//删除的操作
void deleteNode(struct Node* head ,int data) //data为要删除的结点数
{
struct Node* p=head;
struct Node* q=NULL;
while(p!=NULL)
{
if(p->val==data)
{
if(p==head) //要删除的是头结点
head=p->next;
else
q->next=p->next;
}
q=p; //备份
p=p->next;
}
}

京公网安备 11010502036488号