- #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;
- }
注意指针在使用前必须初始化