实现线性表的链式存储定义,完成单链表的创建(头插法、尾插法)、插入、删除、查找等常用操作,将线性链表逆置,即最后一个结点变成第一个结点,原来倒数第二个结点变成第二个结点,以此类推。
时间: 2023-10-19 10:16:25 浏览: 166
链表的相关操作 创建,删除,查找,插入,逆置,等
5星 · 资源好评率100%
线性表的链式存储定义:
```
typedef struct node {
int data;
struct node *next;
} Node, *LinkedList;
```
其中,`data` 表示结点中存储的数据,`next` 表示指向下一个结点的指针,`LinkedList` 表示头结点的指针。
单链表的创建:
头插法:
```
LinkedList createListHead(int n) {
LinkedList head = (LinkedList) malloc(sizeof(Node));
head->next = NULL;
for (int i = 0; i < n; i++) {
LinkedList newNode = (LinkedList) malloc(sizeof(Node));
printf("请输入第%d个结点的值:", i + 1);
scanf("%d", &(newNode->data));
newNode->next = head->next;
head->next = newNode;
}
return head;
}
```
尾插法:
```
LinkedList createListTail(int n) {
LinkedList head = (LinkedList) malloc(sizeof(Node));
head->next = NULL;
LinkedList tail = head;
for (int i = 0; i < n; i++) {
LinkedList newNode = (LinkedList) malloc(sizeof(Node));
printf("请输入第%d个结点的值:", i + 1);
scanf("%d", &(newNode->data));
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
return head;
}
```
插入操作:
在第 i 个结点后插入一个值为 x 的结点:
```
bool insert(LinkedList L, int i, int x) {
LinkedList p = L;
for (int j = 0; j < i - 1; j++) {
p = p->next;
if (p == NULL) {
printf("插入位置不合法\n");
return false;
}
}
LinkedList newNode = (LinkedList) malloc(sizeof(Node));
newNode->data = x;
newNode->next = p->next;
p->next = newNode;
return true;
}
```
删除操作:
删除第 i 个结点:
```
bool delete(LinkedList L, int i) {
LinkedList p = L;
for (int j = 0; j < i - 1; j++) {
p = p->next;
if (p == NULL) {
printf("删除位置不合法\n");
return false;
}
}
LinkedList q = p->next;
if (q == NULL) {
printf("删除位置不合法\n");
return false;
}
p->next = q->next;
free(q);
return true;
}
```
查找操作:
查找值为 x 的结点:
```
LinkedList find(LinkedList L, int x) {
LinkedList p = L->next;
while (p != NULL && p->data != x) {
p = p->next;
}
return p;
}
```
逆置操作:
```
LinkedList reverse(LinkedList L) {
LinkedList newHead = L;
LinkedList p = L->next;
L->next = NULL;
while (p != NULL) {
LinkedList q = p->next;
p->next = newHead->next;
newHead->next = p;
p = q;
}
return newHead;
}
```
阅读全文