链表倒置

来源:互联网 发布:千千静听软件 编辑:程序博客网 时间:2024/05/01 23:10

 

#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;elseq->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;}


注意指针在使用前必须初始化

 

 

原创粉丝点击