链表来实现顺序结构的优势——方便增删,但是不方便改查
下面对链表的初始化链表init,插入元素insert,删除元素delete,查找元素find,进行了展示
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include <stdbool.h>
struct node {
int data;
struct node* next;
};
typedef struct node* position;//这里的位置是节点的地址
typedef struct node* list;//这是链表头节点
list init() {
list head = malloc(sizeof(struct node));
head->next = NULL;
return head;
}
bool insert(list head, int i, int x) {
position pre, tmp;
pre = head;
int cot = 1;
while (pre&&cot<i) {
pre = pre->next;
cot++;
}
//printf("%d======\n", cot);
if (cot !=i || pre == NULL) {
printf("插入位置参数错误!\n");
return false;
}
else {
position value = (position)malloc(sizeof(struct node));
tmp = pre->next;
value->data = x;
value->next = pre->next;
pre->next = value;
free(tmp);
//printf("dadadada\n");
/*if (value->next == NULL) {
printf("NULL\n");
}*/
return true;
}
}
bool delete(list head, int i) {
position pre, tmp;
pre = head;
int cot = 1;
while (pre && cot < i) {
pre = pre->next;
cot++;
}
if (cot != i || pre==NULL) {
printf("插入位置参数错误!\n");
return false;
}
else {
tmp = pre->next;
pre->next = tmp->next;
free(tmp);
return true;
}
}
//这里求链表的长度
int len(list l) {
int len=0;
position p = l;
while (p) {
p = p->next;
len++;
}
return len;
}
//按照序号查找
int findkth(list head, int k) {
position p = head->next;//p指向第头节点
int cot = 1;//序列从1开始
while(p&&cot<k){
p = p->next;
cot++;
}
if (cot == k) {
return p->data;
}
else {
return -1;
}
}
//按照要搜索的值查找
position findx(list head, int x) {
position p = head->next;//p指向第一个节点
while (p->data!=x&&p) {
p = p->next;
}
return p;//因为p一直往后走,跳出循环的条件,一是p为NULL,二是找到了p->data==x,所以直接反回p
}
void show(list head) {
position pre = head->next;
while (pre!=NULL) {
printf("%d ", pre->data);
pre = pre->next;
}
}
int main() {
//测试init,insert,show()
list l = init();
insert(l, 1, 1);
insert(l, 2, 2);
insert(l, 3, 3);
show(l);//打印1 2 3
printf("\n");
delete(l, 1);
show(l);//打印2 3
printf("\n");
//测试find
printf("%d\n",findkth(l, 1));//此时第一位是2,应该打印2
printf("%d\n",findx(l, 3)->data);//findx返回值是position,所指向的data应当是3
return 0;
}