#include <stdio.h>
#include <malloc.h>
typedef struct list{
int value;
struct list *next;
}node;
node* add(node *head) //增加节点
{
node *p = head, *p2;
int tmp;
char ch;
scanf("%d", &tmp);
ch = getchar();
p2 = (node *)malloc(sizeof(node));
p2->value = tmp;
p2->next = NULL;
if (NULL == p)
return p2;
while (p->next != NULL)
p = p->next;
p->next = p2;
return head;
}
node* del(node *head) //删除节点
{
int tmp, flag;
char ch;
node *p = head, *pre = NULL;
if (NULL == p)
{
printf("ERROR! List is NULL!\n");
return head;
}
scanf("%d", &tmp);
ch = getchar();
flag = 0;
while (p)
{
if (p->value == tmp)
{
flag = 1;
break;
}
pre = p;
p = p->next;
}
if (0 == flag)
{
printf("ERROR! There is no %d.\n", tmp);
return head;
}
if(NULL == pre)
{
p = p->next;
free(head);
return p;
}
pre->next = p->next;
free(p);
return head;
}
void print(node *head) //遍历链表
{
node *p = head;
while (p)
{
printf("%d\t", p->value);
p = p->next;
}
printf("\n");
return;
}
node *rev(node *head) //翻转链表
{
node *p = head, *pre = NULL, *tmp;
while (p)
{
tmp = p;
p = p->next;
tmp->next = pre;
pre = tmp;
}
return pre;
}
int main()
{
char c, ch;
node *head = NULL;
printf("a:增加节点;\td:删除节点;\tp:遍历链表;\tr:翻转链表.\n");
while (scanf("%c", &c) != EOF)
{
ch = getchar();
switch (c)
{
case 'a': head = add(head); break;
case 'd': head = del(head); break;
case 'p': print(head); break;
case 'r': head = rev(head); break;
default: printf("Invalid input!\n");
}
printf("a:增加节点;\td:删除节点;\tp:遍历链表;\tr:翻转链表.\n");
}
return 0;
}
链表的基本操作
最新推荐文章于 2022-08-29 14:49:54 发布