单链表基本操作
2013-02-27 10:24
197 查看
单链表的创建、打印、逆置
#include<iostream>
using namespace std;
/*-------------------------结构体定义部分------------------------------*/
typedef struct node
{
int data;
struct node* next;
}listnode;
/*-----------------------------创建链表---------------------------------*/
void createList(node* list,int n)
{
node* head=list;
for(int i=0;i<n;i++)
{
node* temp=(node*)malloc(sizeof(node));
temp->data=i;
list->next=temp;
list=temp;
}
list->next=NULL;
list=head;
}
/*-----------------------------打印链表---------------------------------*/
void printList(node* list)
{
if(list==NULL)
return;
node* p=list->next;
while(p)
{
cout<<p->data<<'\t';
p=p->next;
}
cout<<endl;
}
/*-----------------------------逆置链表---------------------------------*/
void reverseList(node* list)
{
node* p1=NULL;
node* p2=list->next;
node* p3=NULL;
while(p2)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
list->next=p1;
}
int main()
{
node* list;
list=(node*)malloc(sizeof(node));
list->next=NULL;
createList(list,5);
printList(list);
reverseList(list);
printList(list);
return 0;
}
#include<iostream>
using namespace std;
/*-------------------------结构体定义部分------------------------------*/
typedef struct node
{
int data;
struct node* next;
}listnode;
/*-----------------------------创建链表---------------------------------*/
void createList(node* list,int n)
{
node* head=list;
for(int i=0;i<n;i++)
{
node* temp=(node*)malloc(sizeof(node));
temp->data=i;
list->next=temp;
list=temp;
}
list->next=NULL;
list=head;
}
/*-----------------------------打印链表---------------------------------*/
void printList(node* list)
{
if(list==NULL)
return;
node* p=list->next;
while(p)
{
cout<<p->data<<'\t';
p=p->next;
}
cout<<endl;
}
/*-----------------------------逆置链表---------------------------------*/
void reverseList(node* list)
{
node* p1=NULL;
node* p2=list->next;
node* p3=NULL;
while(p2)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
list->next=p1;
}
int main()
{
node* list;
list=(node*)malloc(sizeof(node));
list->next=NULL;
createList(list,5);
printList(list);
reverseList(list);
printList(list);
return 0;
}
相关文章推荐
- 线性链表的基本操作
- 链表的基本操作---创建
- 《线性表---链表的基本操作》
- 单链表、双链表的基本操作
- 数据结构之链表(1):单链表基本操作
- 链表基本操作
- 数据结构学习笔记(二) 链表之链队列基本操作
- 数据结构——单链表基本操作
- 单链表及其基本操作(C语言实现)
- 《实验课---单链表的基本操作》
- 单链表的基本操作
- 【数据结构】-线性表-链表-1326:链表的基本操作【好题】
- 数据结构-顺序表和链表的基本操作
- 【数据结构作业】实验三 单链表的基本操作(必做,设计性实验,4学时)
- C语言链表基本操作
- 单链表的基本操作
- 单链表的基本操作
- 有表头链表的基本操作
- 顺序链表的基本操作
- 单链表基本操作示例1[C语言实现]