通过C++中的引用建立链表
通过C++中的引用建立链表
通过C++中的引用建立链表
通过C++引用语法实现对链表的改动
void change( int &a, int &b)
change(a,b);
int &a 相当于a的别名,er int &a 是双向的可用的在C语言我改变元>素的值通常使用指针改变函数的值,通过传递其地址
代码如下:
#include <iostream>
#include<cstdio>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}link,*linkednode;
// 在此使用头插法完成链表的建立
void CreateLink(linkednode &L)
{
linkednode s;
L=(linkednode)malloc(sizeof(link));
L->next=NULL;
for(int i=0;i<10;i++)
{
s=(linkednode)malloc(sizeof(link));
s->data=i;
// 插入结点信息
s->next=L->next;
L->next=s;
}
}
// 输出结点信息
void printLinkinfo(linkednode &L)
{
linkednode temp;
temp =(linkednode)malloc(sizeof(link));
temp=L;
while(temp->next)
{
printf("%d",temp->data);
temp=temp->next;
}
}
// 使用尾插法建立链表的操作
void CreateLink2(linkednode &L)
{
linkednode s,t;
L=(linkednode)malloc(sizeof(link));
L->next=NULL;
t=L;
int i;
for( i=0;i<10;i++)
{
s=(linkednode)malloc(sizeof(link));
s->data=i;
s->next=NULL;
t->next=s;
t=s;
}
}
// 删除结点信息
void deleteinfo(linkednode &L,int i)
{
linkednode temp ,t;
int j=0;
temp=(linkednode)malloc(sizeof(link));
temp=L;
while(temp->next&&(j<i-1))
{
temp =temp->next;
j++;
}
t=temp->next;
temp->next=t->next;
printf("删除的数据为%d",t->data);
}
void insertinfo(linkednode &L,int loc,int e)
{
int j=0;
linkednode temp,s;
temp=L;
while(temp->next&&j<(loc-1))
{
temp=temp->next;
j++;
}
s=(linkednode)malloc(sizeof(link));
s->data=e;
s->next=temp->next;
temp->next=s;
}
int main()
{
link *L=NULL;
// 头插法
//CreateLink(L);
//尾插法
CreateLink2(L);
// 输出信息
printLinkinfo(L);
printf("\n");
deleteinfo(L,3);
printf("\n");
printLinkinfo(L);
printf("\n");
insertinfo(L,3,6);
printLinkinfo(L);
return 0;
}
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.