您的位置:首页 > 其它

链表的基本操作

2014-08-27 15:54 190 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: