程序代码
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node;
Node *linklist_create()
{
Node *head = (Node*)malloc(sizeof(Node));
if(head == NULL)
{
printf("malloc fail\n");
return NULL;
}
head->data = -1;
head->next = NULL;
return head;
}
Node *node_create(int data)
{
Node *newnode = (Node*)malloc(sizeof(Node));
newnode->data = data;
newnode->next = NULL;
}
void linklist_show(Node *head)
{
Node * pnode = head->next;
while(pnode)
{
printf("%-4d", pnode->data);
pnode = pnode->next;
}
printf("\n");
}
void insert_node(Node *head,int data)
{
Node *newnode = node_create(data);
newnode ->next = head->next;
head->next = newnode;
}
int linklist_insert_data(Node *head, int data, int pos)
{
if (pos < 0 || pos > linklist_length(head))
{
printf("pos is error\n");
return -1;
}
if (head->next == NULL)
{
printf("linklist is empty\n");
return -1;
}
int i = 0;
Node *q = head;
for (i = 0; i < pos; i++)
{
q = q->next;
}
Node *p = (Node *)malloc(sizeof(Node));
p->data = data;
p->next = q->next;
q->next = p;
return 0;
}
int linklist_is_empty(Node *head)
{
if(head->next == NULL)
{
return 1;
}
else
return 0;
}
int linklist_length(Node *head)
{
Node *p = head;
int len = 0;
while(p->next != NULL)
{
len++;
p = p->next;
}
return len;
}
int LlistPoS_delete_data(Node *head, int pos)
{
if (pos < 0 || pos > linklist_length(head))
{
printf("pos is error\n");
return -1;
}
if (head->next == NULL)
{
printf("linklist is empty\n");
return -1;
}
int i = 0;
Node *q = head;
for (i = 0; i < pos ; i++)
{
q = q->next;
}
Node *p = (Node *)malloc(sizeof(Node));
p = q->next;
q->next = p->next;
free(p);
return 0;
}
int main()
{
Node *linklist = linklist_create();
int i;
for(i=0; i<10; i++)
{
insert_node(linklist,i);
}
linklist_show(linklist);
linklist_insert_data(linklist, 55, 3);
linklist_show(linklist);
LlistPoS_delete_data(linklist, 3);
linklist_show(linklist);
system("pause");
}
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191218003841607.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE1MTc0NDM3,size_16,color_FFFFFF,t_70)