研究学习了好久才写出来,我是真的菜。
#include <stdio.h>
#include <stdlib.h>
//typedef struct Node* LList;
struct Node {
int data;
struct Node* next;
};
//初始化节点
void init(struct Node** phead) {
*phead = NULL;
}
//求表长
int getLength(struct Node* head) {
int len = 0;
while (head) {
len++;
head = head->next;
}
return len;
}
//输出链表
void printList(struct Node* head) {
while (head) {
printf("%d,", head->data);
head = head->next;
}
putchar('\n');
}
//根据输入值x创建节点
struct Node* createNode(int x) {
struct Node* t;
t = (struct Node*)malloc(sizeof(struct Node));
t->next = NULL;
t->data = x;
return t;
}
//找第K个元素的值
struct Node* findKth(struct Node* head, int k) {
int count = 0;
struct Node* p;
p = head;
while (p && count < k-1) {
p = p->next;
count++;
}
return p;
}
//插入
int insert(struct Node** phead, int k, int x) {
if (k < 1) {
return 0;
}
else if (k == 1) {
struct Node* t;
t = createNode(x);
t->next = *phead;
*phead = t;
return 1;
}
else {
struct Node* p;
p = findKth(*phead, k - 1);
if (p) {
struct Node* t;
t = createNode(x);
t->next = p->next;
p->next = t;
return 1;
}
else {
return 0;
}
}
}
//删除
int delete (struct Node** phead, int k, int* px) {
if (k < 1) {
return 0;
}
else if (k == 1) {
if (*phead) {
*px = (*phead)->data;
*phead = (*phead)->next;
return 1;
}
else return 0;
}
else {
struct Node* p;
p = findKth(*phead, k - 1);
if (p == NULL || p->next == NULL) {
return 0;
}
struct Node* t;
t = p->next;
p -> next = t->next;
*px = t->data;
free(t);
return 1;
}
}
int main(int argc, const char* argv[])
{
struct Node* head;
init(&head); //初始化链表,改变链表,传指针
//int k = getLength(head); //求表长,不改变链表
//printList(head);
//printf("%d\n", k);
insert(&head, 1, 11);
//insert(&head, 1, 22);
//insert(&head, 2, 33);
//insert(&head, 4, 44);
//insert(&head, 6, 55);
printList(head);
int x;
delete(&head, 2, &x);
printf("%d\n", x);
printList(head);
/*delete(&head, 2, &x);
printf("%d\n", x);
printlist(head);
delete(&head, 2, &x);
printf("%d\n", x);
printlist(head);*/
system("pause");
return 0;
}