链表,别名链式存储结构或单链表,用于存储逻辑关系为 "一对一" 的数据。与顺序表不同,链表不限制数据的物理存储状态,换句话说,使用链表存储的数据元素,其物理存储位置是随机的。
链表的创建及增删改查
#include "stdafx.h"
typedef struct Link {
char elem;
struct Link * next;
}link;
link * initLink() {
//link * p = NULL; //头指针
//link * temp = (link*)malloc(sizeof(link)); //临时节点
link * p = (link*)malloc(sizeof(link));// 头节点用于遍历
link *temp = p;
for (int i = 1; i < 5; i++) {
link * a = (link*)malloc(sizeof(link));
a->elem = i*2;
a->next = NULL;
temp->next = a; //临时节点(前驱)指向 a(后继),存储 a 的位置
temp = temp->next; //临时节点向后移一位
}
return p;
}
void display(link *p) {
link *temp = p->next;
while (temp) {
printf("%d ", temp->elem);
temp = temp->next;
}
printf("\n");
}
link * insertElem(link * p, int elem, int add) {
link * temp = p;
for (int i = 1; i < add; i++) {
if (temp == NULL) {
printf("Invalid address for inserting\n");
return p;
}
temp = temp->next;
}
link *c = (link*)malloc(sizeof(link));
c->elem = elem;
c->next = temp->next;
temp->next = c;
return p;
}
link * delElem(link* p, int add) {
link *temp = p;
for (int i = 1; i < add; i++) {
if (temp == NULL) {
printf("Invalid address for deleting\n");
return p;
}
temp = temp->next;
}
link * del = temp->next;
temp->next = temp->next->next;
free(del);//释放内存
return p;
}
link * updateElem(link *p, int add, int newElem) {
link * temp = p->next;
for (int i = 1; i < add; i++) {
if (temp == NULL) {
printf("Invalid address for updating\n");
return p;
}
temp = temp->next;
}
temp->elem = newElem;
return p;
}
int selectElem(link * p, int elem) {
link * temp = p->next;
int i = 1;
while (temp) {
if (temp->elem == elem)
return i;
temp = temp->next;
i++;
}
return -1;
}
int main() {
printf("初始化链表为:\n");
link *p = initLink();
display(p);
printf("在位置3前插入元素5\n");
insertElem(p, 5, 3);
display(p);
printf("删除位置3的元素\n");
delElem(p, 3);
display(p);
printf("查找元素6所在位置\n");
printf("%d \n", selectElem(p, 6));
printf("将位置3的元素改为10\n");
updateElem(p, 3, 10);
display(p);
return 0;
}
网友评论