链表实现

1.伪代码算法
要插入一个节点,即将上一个节点指向的地址改为要插入的地址,将新的节点指向下一个节点
即 set next(i) to q
set *p to next(i)
set q to next(p)
要删除一个节点,即将(i-1)节点的地址改为(i)节点的地址

set next(i)to next(i-1)
2.C语言尝试实现
typedef struct Node
{
int i;
struct Node *next;

} LNode, *LinkList;
bool InitList(LinkList &L)
{
L = (LNode *)malloc(sizeof(LNode));
if (L == NULL)
{
return false;
}
L->next = NULL;
return true;
}
int GetListLength(LinkList &L)
{

int listlength = 0;
LNode *p = L->next;

while (p)
{
    listlength++;
    p = p->next;
}
return listlength;

}
void HeadInsertList(LinkList &L, int n)
{
int data;

while (n--)
{
    scanf("%d", &data);
    LNode *p = (LinkList)malloc(sizeof(LNode));
    p->i = data;
    p->next = L->next;
    L->next = p;
}

}
void TraverList(LinkList &L)
{
LNode *p = L->next;
while (p)
{
printf("%d ", p->i);
p = p->next;
}
}
Void Changelist(int i)
{
if (i != 0)
*i = *(i - 1);
}

include <stdio.h>

int main()
{
int n;
char c;
typedef struct Node
{
int i;
struct Node *next;

} LNode, *LinkList;
scanf("%d", &n);
printf("do you want to delete ?");
scanf("%c", &c);
if (c == 'n' || c == 'N')
    HeadInsertList(*LinkList, 1); //添加元素
else
    Changelist(i);             //删除元素
void TraverList(LinkList & L); //遍历链表以确定是否修改成功

}
注:代码中链表部分借鉴了https://blog.csdn.net/xinzhilinger/article/details/109011550中的内容

posted @ 2022-10-23 19:17  20221418曾庆林  阅读(5)  评论(0编辑  收藏  举报