2021-01-04 C语言 链表相关

2021.1.4 C语言 链表相关

目标:实现链表的插入与删除
法一

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

typedef struct _node
{
    int num;
    struct _node * next;//定义结构体
}node;

node * createlist(void);//插入函数
void display(node * head);//展示函数
node * Delete(node * head, int x);//删除函数

int main(void)//主函数
{
    node *head;
    head = createlist();
    display(head);
    head = Delete(head, 0);
    display(head);
    return 0;
}

node * createlist(void)
{
    node * head = NULL, *p, *tail = NULL;
    int n;
    while(scanf("%d", &n) == 1)//当输入不为整数时结束
    {
        p = (node *)malloc(sizeof(node));
        
        if(head == NULL)
           head = p;
        else
           tail->next = p;
           
        p->num = n;
        p->next = NULL;
        tail = p;
    }
    return head;
}

void display(node * head)
{
    node * p;
    p = head;
    while(p != NULL)
    {
        printf("%d ",p->num);
        p = p->next;
    }
    printf("\n");
}

node * Delete(node * head, int x)
{
    if(head == NULL)
    {
        printf("链表为空");
        return NULL;
    }
    node * p, * q;
    p = head;
    q = p->next;
    while(q != NULL)
    {
        if(q->num == x)
        {
            p->next = q->next;
            free(q);
            q = p->next;
        }
        else
        {
            p = p->next;
            q = q->next;
        }
    }
    if(head != NULL && head->num == x)
    {
        q = head;
        head = q->next;
        free(q);
        return head;
    }

    return head;
}

答案:

#include <stdio.h>
#include <stdlib.h>
 struct node{
	int num;
	struct node *next;
};

int main(void){
	struct node *head=NULL,*last,*q,*x,*y;
	int num,m;
	do{
		scanf("%d,&num");
		if(num!=-1){
			struct node *p=(struct node*)malloc(sizeof(struct node));
		(*p).num =num;
		(*p).next =NULL;
		if(head==NULL)  head=p;
		else (*last).next =p;
		last=p;
		}
	}while (num!=-1);
	scanf("%d",&m);
	while (head!=NULL&&(*head).num==m){
		y=head;
		head=(*head).next ;
		free(y);
	}
	if(head==NULL) 
    	printf("找不到!"); 
	x=head;
	y=head->next ;
	while(y!=NULL){
		if((*y).num ==m)  {
		(*x).next =(*y).next ;
		free(y);
		}
		else x=y;
		y=(*x).next ;
		
	}
	for (q=head;q!=NULL;q=(*q).next )
		printf("%d",(*q).num );
		return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值