# include <stdio.h>
# include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}Node,*NodeList;
void InitList(NodeList &L) {
L = (Node *)malloc(sizeof(Node));
L->next == NULL;
}
void addList(NodeList &L, int k) {
Node *end = L;
for (int i=0;i<k;i++) {
Node *aa = (Node *)malloc(sizeof(Node));
aa->data = i;
aa->next = NULL;
end->next = aa;
end = aa;
}
}
int Length(NodeList &L) {
Node *head = L->next;
int cc = 0;
while(head!=NULL) {
head = head->next;
cc++;
}
return cc;
}
bool writeList(NodeList &L, int k, int e) {
Node *head = L->next;
int length = Length(L);
if ((k<1)||(k>length+1)) {
return false;
}else {
Node *cc = (Node *)malloc(sizeof(Node));
cc->data = e;
if (k==1) {
cc->next = head;
L->next = cc;
return true;
}else {
for (int i=0;i<k-2;i++) {
head = head->next;
}
cc->next = head->next;
head->next = cc;
return true;
}
}
}
bool DeleteList(NodeList &L, int k, int &e) {
int ll = Length(L);
Node *head = L->next;
if ((k<1)||(k>ll)) {
return false;
}else {
if (k==1) {
L->next = head->next;
e = head->data;
free(head);
return true;
}
for (int i=0;i<k-2;i++) {
head = head->next;
}
Node *c = head->next;
e = head->next->data;
head->next = head->next->next;
free(c);
return true;
}
}
void outputList(NodeList &L) {
Node *head = L->next;
int ll = Length(L);
while(head!=NULL) {
int kk = head->data;
printf("%d - > ", kk);
head = head->next;
}
printf("\n长度: %d\n", ll);
}
int main() {
NodeList L;
InitList(L);
addList(L, 10);
outputList(L);
if (writeList(L, 1, 999)) {
printf("\n插入成功\n");
}else {
printf("\n插入失败\n");
}
outputList(L);
int e = -1;
if (DeleteList(L, 1, e)) {
printf("\n删除成功元素:%d\n", e);
}else {
printf("\n删除失败\n");
}
outputList(L);
}
C语言单链表
最新推荐文章于 2024-04-08 21:58:46 发布