#include<stdio.h>
#include <malloc.h>
typedef struct LNode* PtrNode;
struct LNode {
int data;
PtrNode next;
};
typedef PtrNode list;
list read()//头插法创建链表
{
int n;
list head, tmp, cur;
head = cur = (list)malloc(sizeof(struct LNode));
cur->next = NULL;
scanf_s("%d", &n);
while (n--) {
tmp = (list)malloc(sizeof(struct LNode));
scanf_s("%d", &tmp->data);
tmp->next = NULL;
cur->next = tmp;
cur = tmp;
}
return head;
}
int len(list L)
{
list head;
int count = 0;
head = L;
while (head) {
head = head->next;
count++;
}
return count;
}
int find(list L, int location)
{
int count = 0;
list head;
head = L;
while (head && count < location)
{
head = head->next;
count++;
}
if (count == location)
{
printf_s("the index is %d", head->data);
}
return 0;
}
list insert(list L, int x, int location)
{
list tmp, pre;
int count = 0;
pre = L;
while (pre && count < location )//location从0开始
{
pre = pre->next;
count++;
}
if (pre == NULL || count != location)
{
printf_s("ERROR");
}
else
{
tmp = (list)malloc(sizeof(struct LNode));
tmp->data = x;
tmp->next = pre->next;//去除头结点影响
pre->next = tmp;
return pre;
}
}
list Delete(list L, int i)
{
list tmp, pre;
int count=0;
pre = L;
while (pre && count < i)
{
pre = pre->next;
count++;
}
if (pre->next == NULL||count!=i||pre==NULL)
{
printf_s("ERROR");
}
else
{
tmp = pre->next;
pre->next = tmp->next;
free(tmp);
return pre;
}
}
void Print(list L)
{
while (L)
{
printf_s("%d ", L->data);
L = L->next;
}
}
int main()
{
list L;
L = read();
//find(L, 2);
//printf_s("%d", len(L));
insert(L, 666, 0);
Delete(L, 1);
printf_s("\n");
Print(L);
}
链式线性表数据结构
最新推荐文章于 2023-09-03 22:17:25 发布