#include <iostream>
using namespace std;
typedef struct LNode{
int data;
LNode* next;
}Lnode,*Linklist;
//单链表初始化
Linklist Initiate(){
Linklist L = (Linklist)malloc(sizeof(LNode));
L->next = NULL;
return L;
}
//头插法(带头节点)
void H_CreatLinkList(Linklist &L){
int elem;
Lnode* head = L;
printf("请输入数据:");
while(scanf("%d",&elem) != EOF)
{
Lnode* N = (LNode*)malloc(sizeof(Lnode));
// scanf("%d",&elem);
N->data = elem;
N->next = head->next;
head->next = N;
}
}
//尾插法
void T_CreatLinkList(Linklist &L){
int elem;
Lnode* head = L;
Lnode* r = L;
printf("请输入数据:");
while(scanf("%d",&elem) != EOF)
{
Lnode* N = (LNode*)malloc(sizeof(Lnode));
// scanf("%d",&elem);
N->data = elem;
r->next = N;
r = N ;
}
r->next = NULL;
}
//查找节点
Lnode* FindNode(Linklist &L, int num){
Lnode* p = L->next;
while(p != NULL && p->data != num){
p = p->next;
}
return p;
}
//获取链表长度
int LinkList_Len(Linklist L){
int len =0;
Lnode* p = L->next;
while(p!= NULL){
len++;
p = p->next;
}
return len;
}
//单链表原地逆置
void ReverseList(Linklist &L){
Lnode* p = L->next;
Lnode* tmp = p;
if(p->next){
Lnode* q = p->next;
while(q != NULL){
p->next = q->next;
q->next = tmp;
tmp = q;
q = p->next;
}
}
L->next = tmp;
}
int main(){
Linklist L = Initiate();
T_CreatLinkList(L);
Lnode* p ;
p = L->next;
while(p != NULL){
cout<<p->data<<",";
p = p->next;
}
int len = LinkList_Len(L);
cout<<endl<<"Linklist len:"<<len<<endl;
ReverseList(L);
Lnode* q;
q = L->next;
cout<<" After Reverse:"<<endl;
while(q != NULL){
cout<<q->data<<",";
q = q->next;
}
}
单链表的基本操作
于 2023-09-02 10:33:48 首次发布