链表倒置
发布时间:2020-12-13 20:01:00 所属栏目:百科 来源:网络整理
导读:#include"iostream"using namespace std; struct node{int data;struct node *next;}; typedef struct node Node; node * reverse( node * head){ node * p,*q;p=head-next;head-next = NULL; while(p!=NULL){ q=p; p=p-next; //修改q会修改p所指的值,所以
#include"iostream" using namespace std; struct node { int data; struct node *next; }; typedef struct node Node; node * reverse( node * head) { node * p,*q; p=head->next; head->next = NULL; while(p!=NULL) { q=p; p=p->next; //修改q会修改p所指的值,所以必须先对p进行保护 q->next = head->next; head->next=q; } return head; } int main() { node head,*p,*q; int i; head.next=NULL; for(i=0;i<10;i++) { p = new node; p->next=NULL; p->data=i; if(head.next==NULL) head.next=p; else q->next=p; q=p; } p=head.next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; p= reverse(&head); p=p->next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; return 0; } 注意指针在使用前必须初始化 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |