双链表 基操!
最近博主在学习数据结构,在双链表的创建卡了壳,博主所看的书籍上也没有关于双链表创建的操作,于是乎,网上浏览资料,但大神写的代码,实非博主菜鸟之辈所能轻易看懂,于是在请教之后,博主终于学会了双链表之基操,博主个人感觉比较适合初学者。博主不才,代码献上:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct info {
info *lnode,*rnode;
char name[255];
long long int phone;
int size=0;
}info;
info *init()
{
return NULL;
}
info *cin()
{
info*pre=nullptr,*next=nullptr,*head= (info*)malloc(sizeof(info));
int i = 0,length;
head->lnode = nullptr; head->rnode = nullptr;
printf("请输入长度:\n");
scanf_s("%d",&length);
if (length == 0)
{
return NULL;
}
else if (length < 0)
{
exit(0);
}
else {
printf("请依次输入联系人的手机号码 姓名\n");
scanf_s("%lld %s", &head->phone, head->name, 20);
i++;
head->lnode = nullptr; head->rnode = nullptr;
pre = head;
while (i < length)
{
next = (info*)malloc(sizeof(info));
printf("请依次输入联系人的手机号码 姓名\n");
scanf_s("%lld %s", &next->phone, next->name, 20);
pre->rnode = next; next->lnode = pre; pre = next;
next = next->rnode;
i++;
}
pre->rnode = nullptr;
return head;
}
}
info*find(info*head, int n)
{
info*p; int i = 1; p = head;
while (p&&i < n)
{
p = p->rnode;
i++;
}
if (i < n)
{
printf("第%d个节点不存在\n", n);
return NULL;
}
else
return p;
}
info*insert(info*head)
{
info*p, *q; int i;
p = (info*)malloc(sizeof(info));
printf("请依次输入需保存的联系人的手机号码 姓名 顺序号\n");
scanf_s("%lld %s %d", &p->phone, p->name,20,&i);
if (i <= 0)
{
printf("Error!\n");
return head;
}
else if (i == 1)
{
p->lnode = nullptr;
if (!head)
{
head = p; head->lnode = nullptr; head->rnode = nullptr;
}
else
{
p->rnode = head;
head->lnode = p; head = p;
}
return head;
}
else {
q = find(head, i);
if (!q) {
printf("第%d个节点不存在,无法插入\n", i);
}
else if (q->rnode == NULL)
{
q->rnode = p;
p->rnode = NULL;
p->lnode = q;
return head;
}
else {
p->rnode = q->rnode;
q->rnode->lnode = p;
q->rnode = p;
p->lnode = q;
return head;
}
return head;
}
}
info*dele(info*head)
{
info*p, *q; int i;
p = (info*)malloc(sizeof(info));
printf("请输入需删除的联系人的顺序号:");
scanf_s("%d",&i);
if (i<=0)
{
exit(0);
}
q = find(head, i);
if (!q) {
printf("第%d个节点不存在,无法操作\n", i);
}
else if (q->rnode == NULL)
{
q->lnode->rnode = NULL;
free(q);
return head;
}
else {
q->lnode->rnode = q->rnode;
q->rnode->lnode = q->lnode;
free(q);
return head;
}
return head;
}
void print(info*head)
{
info*p;
p = head;
while(p)
{
printf("%lld ",p->phone);
printf("%s", p->name);
printf("\n");
p = p->rnode;
}
}
int main()
{
info *head = nullptr;
head=cin();
head=insert(head);
print(head);
system("pause>nul");
return 0;
}