#include <stdio.h>
int nodeNum = 5;
struct node
{
int t;
node * link;
};
//建表
struct node *creatlist()
{
int i = 0;
int t;
struct node *head, *p, *q;
//头结点
scanf_s("%d", &t);
head = new struct node;
head->t = t;
head->link = 0;
q = head;
for (i = 0; i < nodeNum - 1; i++) {
scanf_s("%d", &t);
p = new struct node;
p->t = t;
p->link = 0;
q->link = p;
q = q->link;
}
return head;
}
//删除
struct node *deleteOne(struct node *head, int i)
{
if (head == 0) {
printf("这是个空表\n");
return head;
}
else if (i<0 || i>nodeNum) {
printf("指定元素不存在\n");
return head;
}
//可以删除
struct node *q;
if (i == 0) {
q = head;
head = head->link;
}
else{
struct node *p;
p = head;
for (int j = 0; j < i - 1; j++) {
p = p->link;
}
q = p->link;
p->link = q->link;
}
delete q;
return head;
}
//打印
void print(struct node *head)
{
struct node *tmp;
tmp = head;
while (tmp != NULL)
{
printf("%d ", tmp->t);
tmp = tmp->link;
}
printf("\n");
}
//释放
void removeAll(struct node *head)
{
struct node*p = head;
while (head) {
p = head;
head = head->link;
delete p;
}
}
int main()
{
int i;
struct node *head = NULL;
struct node *h = NULL;
//创建单链表
printf("输入5个值\n");
head = creatlist();
//删除
printf("删除第几个元素\n");
scanf_s("%d", &i);
i = i - 1;
head = deleteOne(head, i);
//head = deleteOne(h, i);//空链表
//打印单链表
printf("删除后的链表为:\n");
print(head);
//释放
removeAll(head);
return 0;
}