#include <stdio.h>
#include <stdlib.h>
/* 下面的单链表是带头节点的 */
typedef int elementType;
struct listNode {
elementType data;
struct listNode *next;
};
typedef struct listNode list;
// 函数声明
int insert (list *tmp, elementType x, int pos);
void print (list *tmp);
int getLength (list *tmp);
int delete (list *tmp, int pos);
int main () {
int i;
list *head = (list*)malloc(sizeof(list));
head->next = NULL;
// 循环插入测试数
for (i=1; i<=10; i++) {
insert(head, i+2, 1);
}
print(head);
insert(head, 999, 11);
print(head);
delete(head, 1); //删除第1个节点
printf("删除节点后的效果
");
print(head);
return 0;
}
// 插入
// 参数说明: 要插入的链表 插入值 插入位置
// pos的合法取值范围是 [1, length+1]
// 取值为1代表插入到第1个节点之前, 取值为length+1代表插入到表尾
int insert (list *tmp, elementType x, int pos) {
list *ptr; // 存取指针
list *cur; // 存放新节点
int count = 1; // 计数
int length = getLength(tmp);
if (pos < 1 || pos > length + 1) {
printf("插入位置错误
");
return -1;
}
ptr = tmp; // ptr指向头结点
while (count < pos) {
ptr = ptr->next; // 循环结束后ptr指向 pos-1 节点
count++;
}
cur = (list*)malloc(sizeof(list));
cur->data = x;
cur->next = ptr->next;
ptr->next = cur;
return 0;
}
// 得到链表的长度
int getLength (list *tmp) {
int length = 0;
tmp = tmp->next;
while (tmp != NULL) {
length++;
tmp = tmp->next;
}
return length;
}
// 循环打印输出链表信息
void print (list *tmp) {
list *head = tmp;
tmp = tmp->next;
printf("链表长度为: %d
", getLength(head));
printf("链表中的数据:
");
while (tmp != NULL) {
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("
");
printf("
");
}
// 删除
// 删除给定位置上的节点
int delete (list *tmp, int pos) {
int length = getLength(tmp);
if (pos < 1 || pos > length) {
printf("删除位置错误
");
return -1;
}
int count = 1;
list *ptr;
list *posCur; // 存放要删除节点的指针
ptr = tmp;
// 找到 pos-1 这个节点
while (count < pos) {
ptr = ptr->next;
count++;
}
// 循环结束后 ptr 指向 pos-1 这个节点
posCur = ptr->next;
ptr->next = posCur->next;
free(posCur);
return 0;
}