链表的逆转(头插法)

来源:互联网 发布:淘宝网拍模特兼职 编辑:程序博客网 时间:2024/05/14 16:00


最主要的部分:

void reverse(node*head){    node*p,*q;    p=head->next;    head->next=NULL;    while(p)    {        q=p;        p=p->next;        q->next=head->next;        head->next=q;    }} 

#include<stdio.h>#include<malloc.h>#include<iostream>using namespace std;typedef struct node{    int data;    struct node*next; }node; node*creat() {    node*head,*p,*q;    char ch;    head=(node*)malloc(sizeof(node));    q=head;    ch='*';    puts("单链表尾插法,?结束");    while(ch!='?')    {        int a;         cin>>a;        p=(node*)malloc(sizeof(node));        p->data=a;        q->next=p;        q=p;        ch=getchar();     }     q->next=NULL;     return(head); } void print(node*a) {    puts("print ");    a=a->next;    while(a!=NULL)    {        printf("%d ",a->data);        a=a->next;     }  } void reverse(node*head){    node*p,*q;    p=head->next;    head->next=NULL;    while(p)    {        q=p;        p=p->next;        q->next=head->next;        head->next=q;    }}  int main() {    node*a;    a=creat();    print(a);    reverse(a);    puts("\nhaved reversed:");     print(a);     return 0; }