求链表的长度
int Length(LNode *head)//求链表的长度
{
LNode *p = head;
int len = 0;
while(p->next)
{
p = p->next;
len ++;
}
return len;
}
按序号查找,找到返回指向结点的指针,否则返回NULL
LNode *GetElem(LNode *head,int i)//按序号查找,找到返回指向结点的指针,否则返回NULL
{
LNode *p = head;
int j = 0;
while(p->next&&j<i)
{
p = p->next;
j ++;
}
if(j == i) return p;
else return NULL;
}
按值查找
LNode *LocateElem(LNode *head,ElemType x)//按值查找
{
LNode *p=head->next;
while(p&&p->data!=x)
{
p=p->next;
}
/*or
while(p->next&&p->data!=x)
p=p->next;
if(p->data==x) return p;
else return NULL;
*/
return p;
}
完整代码
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct node//单链表节点类型定义
{
ElemType data;
struct node *next;
}LNode;
LNode *create(int n)//创建链表
{
int i;
LNode *head,*pnew,*prear;//最后一个指向尾节点
head = (LNode*)malloc(sizeof(LNode));
head ->next = NULL;
prear = head;
for(int i = 0;i < n;i ++)
{
pnew = (LNode*)malloc(sizeof(LNode));//申请新插入元素的空间
scanf("%d",&pnew->data);
prear -> next = pnew;
prear = pnew;
}
prear -> next = NULL;
return head;
}
void output(LNode *head)
{
LNode *p = head->next;
while(p != NULL)//or(p)
{
printf("%d ",p->data);
p = p->next;//指向它的next指针
}
}
int Length(LNode *head)//求链表的长度
{
LNode *p = head;
int len = 0;
while(p->next)
{
p = p->next;
len ++;
}
return len;
}
LNode *GetElem(LNode *head,int i)//按序号查找,找到返回指向结点的指针,否则返回NULL
{
LNode *p = head;
int j = 0;
while(p->next&&j<i)
{
p = p->next;
j ++;
}
if(j == i) return p;
else return NULL;
}
LNode *LocateElem(LNode *head,ElemType x)//按值查找
{
LNode *p=head->next;
while(p&&p->data!=x)
{
p=p->next;
}
/*or
while(p->next&&p->data!=x)
p=p->next;
if(p->data==x) return p;
else return NULL;
*/
return p;
}
int menu()//打印菜单
{
int choose;
printf("|------单链表基本操作------|\n");
printf("|-------1.求表长-------|\n");
printf("|-------2.按位置查找---------|\n");
printf("|-------3.按值查找-------------|\n");
printf("|-------4.插入-------------|\n");
printf("|-------5.删除-------------|\n");
printf("|-------6.有序表插入-------|\n");
printf("|-------7.有序表删除-------|\n");
printf("|-------0.退出-------------|\n");
do{
printf("请输入你的选择(0~7):\n");
scanf("%d",&choose);
}while(choose<0||choose>7);
return choose;
}
void frame()
{
int n,i;
LNode *head,*p;
scanf("%d",&n);
head=create(n);
output(head);
while(1)
{
switch(menu())
{
case 0:exit(0);
case 1:
{
printf("length=%d\n",Length(head));
break;
}
case 2:printf("Input search's position:");
scanf("%d",&i);
p=GetElem(head,i);
if(p)
printf("第%d个位置的元素值是:%d\n",i,p->data);
else
printf("查找失败!\n");
break;
case 3:printf("Input search's elem:\n");
scanf("%d",&i);
p=LocateElem(head,i);
if(p)
printf("元素值是:%d\n",p->data);
else
printf("查找失败!\n");
break;
case 4:break;
case 5:break;
case 6:break;
case 7:break;
}
}
}
int main()
{
int n,i;
LNode *head,*p;
scanf("%d",&n);
head = create(n);
output(head);
printf("\n");
printf("length=%d\n",Length(head));
printf("Input search's position:");
scanf("%d",&i);
p=GetElem(head,i);
if(p)
printf("第%d个位置的元素值是:%d\n",i,p->data);
else
printf("查找失败!\n");
return 0;
}