数据结构(C语言) 设有一个线性表E,将线性表逆置,要求逆线性表占用原线性表空间,用顺序和单链表分别表

2025-01-05 19:59:21
推荐回答(1个)
回答(1):

输入数据,输出数据,及线性表的长度,
询问是否查找数据,若查找则由用户输入需查找的数据,显示此数据在线性表中的位置(第几个)
*/
#include
#include
#define NULL 0
#define LEN sizeof(struct Node)
struct Node
{
int num;
struct Node* next;
};
struct Node *createline();
void showline(struct Node *head);
int getlen(struct Node *head);
int selectline(struct Node *head,int data);
int main()
{
struct Node *head;
int selflag;
int len = 0;
head = createline();
if(head == NULL)
{
printf("create error\n");
return 1;
}
showline(head);
printf("line's len is %d\n",getlen(head));
printf("0 select,other not select\n");
scanf("%d",&selflag);
if(selflag == 0)
{
printf("请输入要查找的数字:");
scanf("%d",&selflag);
len = selectline(head,selflag);
if(len < 0)
{
printf("无此数据\n");
}
else
{
printf("此数据在第%d个位置\n",len);
}
}
return 0;
}

struct Node *createline()
{
struct Node *head = NULL,*p1,*p2;
int len;
int i;
printf("请输入要插入数据的个数:");
scanf("%d",&len);
if(len <= 0 )
{
printf("len error\n");
return NULL;
}

for(i = 0; i < len; ++i)
{
p1 = (struct Node*)malloc(LEN);
printf("请输入第%d个数据:",i+1);
scanf("%d",&p1->num);
p1->next = NULL;
if(i == 0)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
}

return head;
}
void showline(struct Node *head)
{
struct Node *p1;
p1 = head;
while(p1)
{
printf("%d ",p1->num);
p1 = p1->next;
}
printf("\n");
return ;
}
int getlen(struct Node *head)
{
int len = 0;
struct Node *p1;
p1 = head;
while(p1)
{
len += 1;
p1 = p1->next;
}
return len;
}

int selectline(struct Node *head,int data)
{
int len = 1;
int flag = 0;
struct Node *p1;
p1 = head;
while(p1)
{
if(p1->num == data)
{
flag = 1;
break;
}
len += 1;
p1=p1->next;
}
if(flag == 0)
{
len = -1;
}
return len;
}
另外,站长团上有产品团购,便宜有保证