将单链表H逆置

来源:互联网 发布:js中怎么给input赋值 编辑:程序博客网 时间:2024/05/23 12:43

逆置:是指节点间的关系相反,即前驱变后继而后继变前驱。

算法思路:

依次从原链表中取出每个节点,每次都把该节点作为第一个节点插入另一个新链表中。

#include<iostream>#include<stdlib.h>#include<stdio.h>using namespace std;struct node{    int data ;    struct node * next ;} ;//建立单链表,返回头结点struct node * CreateLinkList(){    char ch ;    int x ;    struct node  * head ;    struct node * r , * P ;    head = (struct node *)malloc(sizeof(struct node)) ;    head->next  = NULL ;    r = head ;    ch =getchar( ) ;    while(ch != '*'){      //  cout<<"ch = " << ch<< endl;        scanf("%d" , & x) ;       // cout<<"x = " << x << endl;        P = (struct node *)  malloc(sizeof(struct node)) ;        P->data = x ;        P->next = NULL ;        r->next = P ;        r = r-> next ;        ch = getchar( ) ;    }    return head ;}//将单链表head逆置,并返回逆置后的链表struct node * reverseLinkList(struct node * head ){    struct node *f , * b  , *r;   // b = (struct node *)malloc(sizeof(struct node));    f = head->next;    b->next = NULL ;    head->next = NULL ;    while(f != NULL){        r = f ; //取节点//        cout<<"f->data = "<< f->data << endl;//        cout<<"f->next = " << f->next << endl;        f = f->next ;        r->next = b->next ; //插入节点        b->next = r ;    }   return b ;}int main(){    cout<< "建立单链表(请输入:[空格]25 45 18 76 29*)"<< endl;    struct node * rr =CreateLinkList();    PutOut(rr) ;    struct node * qq ;    cout<<"输出逆置的单链表"<< endl;    qq = reverseLinkList(rr) ;    PutOut(qq) ;   return 0 ;}



0 0
原创粉丝点击