#include
#include
typedef struct node
{
char ch;
struct node *pNext;
}Node;
int main()
{
char ch;
Node *p=NULL;//pointer to a node
Node *head=NULL;//pointer to the head of the list;
Node *tail=NULL;
int count=1;
printf("请输入节点值,以“ #” 号结束\n:");
scanf("%c",&ch);
while(ch!='#')
{
p=(Node*)malloc(sizeof(Node));
p->ch=ch;
p->pNext=NULL;
if(head==NULL)
{
head=tail=p;
}
else
{
tail->pNext=p;
tail=p;
}
scanf("%c",&ch);
}
//display
p=head;
printf("你输入的链表是:\n ");
while(p!=NULL)
{
printf("%c ",p->ch);
p=p->pNext;
}
fflush(stdin);
printf("\n请输入你要查找的节点\n:");
scanf("%c",&ch);
p=head;
while(p!=NULL)
{
if(p->ch!=ch)
{
p=p->pNext;
count++;
}
else break;
}
if(p==NULL)printf("该值的序号是:0\n");
else printf("该值的序号是%d\n",count);
p=head;
while(p!=NULL)
{
head=p->pNext;
free(p);
p=head;
}
return 1;
}
#include "stdio.h"
#include "malloc.h"
#define null 0
struct node /*定义结构体*/
{int data;
struct node *next;
};
struct node *head;
struct node *p;
struct node *s;
void creat() /*创建单链表*/
{int ch;
head=(struct node *)malloc(sizeof(struct node));
head->next=null;
p=head;
printf("请输入数据: ");
scanf("%d",&ch);
while(ch!=-1)
{s=(struct node *)malloc(sizeof(struct node));
s->data=ch;
s->next=null;
p->next=s;
p=s;
printf("请输入数据: ");
scanf("%d",&ch);
}
}
void outline() /*输出单链表*/
{p=head->next;
while(p!=null)
{printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int locate(int x) /*按值查找*/
{p=head->next;
while((p!=null)&&(p->data!=x))
p=p->next;
if(p==null) return 0;
else return (p->data);
}
main() /*主函数*/
{int a=0;
creat();
outline();
printf("请输入你要找的数:\n");
scanf("%d",&a);
printf("你要找的数的下标是: %d\n",locate(a));
printf("结点个数是: %d\n",countnode());
}
建议找本书