面试题(链表)
住:链表在一些公司的笔试中很容易出现的知识点
1.创建一个备用的结构体:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#define LEN sizeof(struct NodeLink)
struct NodeLink{ //链表结构
int id;
float score;
struct NodeLink* next;
};
int n = 0;
2.链表的创建和添加数据:
struct NodeLink* create()//!< 创建链表添加数据
{
struct NodeLink *head;
struct NodeLink *p1,*p2;
p1 = p2 = (struct NodeLink*)malloc(LEN*120);
printf("请输入您的id号:");
scanf("%d",&p1->id);
printf("请输入您的成绩:");
scanf("%f",&p1->score);
head = NULL;
while (p1->id)
{
n++;
if (n==1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (struct NodeLink*)malloc(LEN*120);
printf("请输入您的id号:");
scanf("%d",&p1->id);
printf("请输入您的成绩:");
scanf("%f",&p1->score);
}
p2->next = NULL;
return (head);
}
3.写出程序把一个链表中的节点顺序倒排(在笔试中经常出现)
struct NodeLink *inverted(struct NodeLink *stHead)
{ //!< 顺序倒排
struct NodeLink *p,*q,*r;
p=stHead;
q=p->next;
while(q!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
stHead->next=NULL;
stHead=p;
return stHead;
}
4.写出程序删除链表中的所有接点
struct NodeLink* deleteAll(struct NodeLink *stHead)
{//!< 删除链表中全部节点
struct NodeLink* p;
p = stHead;
while (p != NULL)
{
p = stHead->next;
free(stHead);
stHead = p;
}
return (stHead);
}
5.打印链表中全部的数据:
void display(struct NodeLink *stHead)//!< 打印数据
{
struct NodeLink *p;
p = stHead;
while (p != NULL)
{
printf("\t id:%02d \t成绩:%03.2f\n",p->id,p->score);
p = p->next;
}
}
最后:在main函数中将上述的代码整合在一起
main
int main(int argc, char argv[])
{
struct NodeLink *stHead,*stTest;
stHead = create();
//!< 打印事件
printf("打印结果为:\n");
display(stHead);
printf("\b=====================\n");
stTest = inverted(stHead);
display(stTest);
printf("删除全部数据后:\n");
display(deleteAll(stHead));
getchar();
return 0;
}
运行结构如下图所示:
感谢大家,希望上诉内容可以帮助到你们!