链表的创建遍历插入删除

#ifndef  LINKLIST_H
#define  LINKLIST_H
struct Student {
    int num;
    struct Student* pnext;
};

struct Student* initlink();
int pianli(struct Student* x);
void charu(struct Student* x, int num);
void shanchu(struct Student* x, int num);
#endif


#include <stdio.h>
#include <stdlib.h>
#include"linklist.h"
#include"linklist.h"
struct Student* initlink() {
    struct Student* head = NULL;
    struct Student* tail = NULL;
    struct Student* new = NULL;
    int i;
    head = (struct Student*)malloc(sizeof(struct Student));
    head->num = 0;
    tail = head;
    for (i = 0; i < 5; i++) {
        new = (struct Student*)malloc(sizeof(struct Student));
        new->num = i + 1;
        tail->pnext = new;
        tail = new;
    }
    return head;
}
int pianli(struct Student* x) {
    struct Student* p = NULL;
    for (p = x; p != NULL; p = p->pnext) {
        printf("%d ", p->num);
    }
}
void charu(struct Student* x, int num) {
    struct Student* p = NULL;
    struct Student* new = NULL;
    new = (struct Student*)malloc(sizeof(struct Student));
    new->num = 66;
    for (p = x; p != NULL; p = p->pnext) {
        if (num == p->num) {
            new->pnext = p->pnext;
            p->pnext = new;
            break;
        }
    }
}
void shanchu(struct Student* x, int num) {
    struct Student* p = NULL;
    struct Student* tmp = NULL;
    for (p = x; p != NULL; p = p->pnext) {
        if (p->pnext->num == num) {
            tmp = p->pnext;
            p->pnext = tmp->pnext;
            free(tmp);
            break;
        }
    }
}
#include <stdio.h>
#include <stdlib.h>
#include"linklist.h"
#include"linklist.h"
int main() {
    struct Student* head = NULL;
    head = initlink();
    pianli(head);
    charu(head, 3);
    printf("\n");
    pianli(head);
    shanchu(head, 3);
    printf("\n");
    pianli(head);
    return 0;
}

运行结果:

 

链表创建思路:定义3个结构体指针变量head,tail,new,先malloc一块区域,让head指向这块区域,head给head赋值,然后使tail也指向这块区域。接着进入循环:malloc一块区域,让new指向这块区域,接着给new赋值,让tail->pnext=new,接着让tail也指向这块区域,以此循环,直到tail->pnext=NULL。

链表遍历思路:定义一个结构体指针变量p,让p先指向head,然后指向pnext,然后不断指向下一个pnext,直到pnext=NULL。

链表插入思路:1.定义一个结构体指针变量new

                         2.new->pnext=p->pnext;

                         3.p->pnext=new。

 

链表删除思路:1.定义一个结构体指针变量tmp;

                          2.p->pnext=tmp->pnext;

                          free(tmp)。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值