单链表的创建
有两种,分别是头插和尾插。(c++实现)
1. 头插法
#include<iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
} LNode, *LinkList;
LinkList List_HeadInsert(LinkList &L) {
LNode *s;
int x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
cin >> x;
while(x!=999){
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
cin >> x;
}
return L;
}
void List_print(LinkList &L){
LNode *s = L;
while(L->next!=NULL){
s = s->next;
cout << s->data << " ";
}
}
int main(){
LinkList L;
L = List_HeadInsert(L);
List_print(L);
return 0;
}
2. 尾插法
#include<iostream>
using namespace std;
typedef struct LNode {
int data;
struct LNode *next;
} LNode,*LinkList;
LinkList List_ToolInsert (LinkList &L){
int x;
L = (LinkList)malloc (sizeof(LNode));
LNode *s,*r = L;
cin >> x;
while(x!=999){
s = (LNode *)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
cin >> x;
}
r->next = NULL;
return L;
}
void List_print(LinkList &L){
LNode *s = L;
while(s->next!=NULL){
s = s->next;
cout << s->data << " ";
}
}
int main(){
LinkList L;
L = List_ToolInsert(L);
List_print(L);
return 0;
}
本文详细介绍了使用C++实现单链表的两种方法:头插法和尾插法。通过具体代码示例,展示了如何创建单链表,并提供了打印链表元素的方法。
&spm=1001.2101.3001.5002&articleId=107702751&d=1&t=3&u=a9742c0a10c94164b370c36507f2334f)
5393

被折叠的 条评论
为什么被折叠?



