链表的逆转(头插法)


最主要的部分:

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


你可能感兴趣的:(链表的逆转(头插法))