您的位置:首页 > 其它

链表创建、反转

2015-10-05 11:17 190 查看
#include<stdio.h>
#include<iostream>
// 定义链表结点
using namespace std;
typedef struct node{
node *next;
int data;
}*pnode;
//初始化结点
pnode initialnode(int  n){
pnode head = (pnode)malloc(sizeof(node));
if(head == NULL){
cout<<"分配失败";
exit(1);
}
pnode p = head,q;
for (int i = 2; i <= n; i++){
cin>>p->data;
q = (pnode)malloc(sizeof(node));
p->next = q;
p = q;
}
cin>>p->data;
p->next=NULL;
return head;
}
//打印结点
void printnode(pnode head){
if (head == NULL)
cout<<"empty linknode"<<endl;
else{
pnode p=head;
while(p != NULL){
printf("%d->",p->data);
p = p->next;
}
cout<<"NULL"<<endl;
}
}
//链表反转
pnode reversenode( pnode head){
pnode p,q,l; // l为中间结点,p反转前结点指针,q为反转后结点指针,通过l把p和q联系起来
q=p=l=head;
p=p->next;
q->next=NULL;
while(p != NULL){
l=p;
p = p->next;
l->next = q;
q = l;
}
head = q;
return head;
}
int main(){
int n;
scanf("%d",&n);
pnode head;
head=initialnode(n); //
printnode(head);
head=reversenode(head);
printnode(head);
free(head); //释放结点
return 0;
}


// 有关链表操作,持续更新中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: