bosthhe1 / -

数据结构与算法(初阶)
0 stars 0 forks source link

初识链表 #2

Open bosthhe1 opened 1 year ago

bosthhe1 commented 1 year ago

源.cpp

include"phead.h"

void test() { Stu *s = NULL; SListAhead(&s, 1);//头插 SListinsertTail(&s, 1);//尾插 SListAheadExit(&s);//头删 SListTailExit(&s);//尾删 SListMidInsert(&s,1,30);//中间插 SListModify(&s, 3, 30);//修改 SListSereach(s, 2);//查找 SListProint(s);//打印 }

int main() { test(); return 0; }

bosthhe1 commented 1 year ago

源1.cpp

include"phead.h"

void SListinsertTail(Stu p, int a) { Stu newnode = (Stu)malloc(sizeof(Stu)); newnode->x = a; newnode->next = NULL; if (p ==NULL) p = newnode; else { Stu tail = p; while (tail->next != NULL) { tail = tail->next; } tail->next = newnode; } } void SListTailExit(Stu p) { Stu tail = p; if (tail == NULL) { return; } if (tail->next == NULL) { p = NULL; } else { Stu prev = NULL; while (tail->next != NULL) { prev = tail; tail = tail->next; } free(tail); tail = NULL; prev->next = NULL; } } void SListAhead(Stu s, int x) { Stu p = (Stu )malloc(sizeof(Stu)); p->x = x; p->next = s; s = p; } void SListAheadExit(Stu p) { Stu s = p; if (s == NULL) { return; } if (s->next == NULL) { p = NULL; free(s); } else if (s->next != NULL) { p = s->next; free(s); } } void SListModify(Stu* p, int x, int y) { Stu pp = p; while (pp->x != 3) { pp = pp->next; } pp->x = y; pp = NULL; } void SListSereach(Stu s, int x) { Stu *pos = s; int i = 0; if (pos == NULL) {

    return;
}
else
{
    while (pos->next != NULL)
    {

        if (pos->x == x)
        {
            i++;
            printf("第 %d 个2的位置为= %p\n", i, pos->next);
        }
        pos = pos->next;
    }
    if (i == 0)
    {
        printf("不存在该元素");
    }
}

} void SListMidInsert(Stu *s, int x,int y) { if (s != NULL) { Stu i = (Stu )malloc(sizeof(Stu)); i->x = y; i->next = NULL; Stu pos = s; Stu Mod = s; while ((pos->x) != x&&pos->next != NULL) { Mod = pos; pos = pos->next; }

    if (pos->next == NULL)
    {
        return;
    }
    i->next = pos;
    pos = NULL;
    Mod->next = i;
}

} void SListProint(Stu p) { Stu phead = p; while (phead != NULL) { printf("%d->", phead->x); phead = phead->next; } printf("NULL\n"); }

bosthhe1 commented 1 year ago

head.h

include

include

include

typedef struct Stu { int x; Stu next; }Stu; void SListinsertTail(Stu p, int x); void SListProint(Stu p); void SListTailExit(Stu p); void SListAhead(Stu p,int x); void SListAheadExit(Stu p); void SListModify(Stu p, int x, int y); void SListSereach(Stu s,int x); void SListMidInsert(Stu *s,int x,int y);