您的位置:首页 > 其它

单链表基本操作

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: