链表问题!!!!
建立一个单链表,要求实现以下功能:查找元素为X的节点,求单链表的长度,插入一个元素值为X的结点,删除元素值为X的结点!!!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node{
int val;
char name[20];
struct _node *next;
}node;
void insertnode(node **head, int data, char *name)
{
node *tmp;
node *p = (node *)malloc(sizeof(node));
p->val = data;
strcpy(p->name, name);
p->next = *head;
*head = p;
}
node *findnode(node *head, int key)
{
while(head)
{
if (head->val == key)
{
return head;
}
head = head->next;
}
return NULL;
}
int getnodelen(node *head)
{
int ret = 0;
while(head)
{
ret ++;
head = head->next;
}
return ret;
}
int deletenode(node **head, int data)
{
node *cur = *head, *pre = *head;
while(cur)
{
if (cur->val == data)
{
if(cur == *head)
{
*head = cur->next;
}else
{
pre->next = cur->next;
}
free(cur);
printf("delet successful!\n");
return 1;
}
pre = cur;
cur = cur->next;
}
printf("didn't node, delet faile!\n");
return 0;
}
void deleteall(node *head)
{
node *p;
while(head)
{
p = head->next;
free(head);
head = p;
}
}
void print(node *head)
{
while(head)
{
printf("name : %s val : %d\n", head->name, head->val);
head = head->next;
}
}
int main(void)
{
int cnt, val;
char name[20];
node *head = NULL, *p;
while(scanf("%d", &val) == 1)
{
scanf("%s", name);
insertnode(&head, val, name);
}
while(getchar() != '\n');
cnt = getnodelen(head);
printf("cnt = %d\n", cnt);
printf("input elem val : ");
scanf("%d", &val);
if ((p = findnode(head, val)) != NULL)
{
printf("name : %s\n", p->name);
}
printf("input delete elem val : ");
scanf("%d", &val);
printf("before delete : \n");
print(head);
deletenode(&head, val);
printf("after delete : \n");
print(head);
deleteall(head);
}
小写了一下,测一下吧,希望对你有帮助~~~囧。。。好像又有种帮人做作业的感觉呀。。。汗