线性表——逆转链表结点链接方向(原地逆转)

 

//"LinkList.h"
#include<iostream>
using namespace std;

#define ElemType int

typedef struct LNode{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;

string InitList(LinkList &L){
    L = new LNode;
    L->next = NULL;
    return "OK";
}

string ListInsert(LinkList &L,int i,ElemType e){
    LinkList P = L;
    int j=0;
    while (P && (j<i-1))
    {       
        P = P->next;++j;    
    }
    LinkList S = new LNode;
    S->data = e;
    S->next=P->next;
    P->next=S;
    return "OK";   
}

LNode* GetElement(LinkList L,int i){
    LinkList p = L->next;
    int j = 1;
    while(p && j<i){
        p=p->next;
        j++;
    }
    // if(!p||j>i){
    //     return -1;
    // }
    return p;
}

string DeleteList(LinkList &L,int i){
    LinkList p = L;
    int j = 0;
    while ((p->next)&&(j<i-1))
    {
        p=p->next;
        j++;
    }
    if(!(p->next)||(j>i-1))
        return "ERROR";
    LinkList q = p->next;
    p->next=q->next;
    delete q;
    return "OK";
    
}

string ShowList(LinkList L){
    LinkList p= L;
    while(p->next){
        p=p->next;
        cout<<p->data;
    }
    return "OK";
}

string FillList(LinkList &L){
    
    int p =1;
    char a = '1';
    while (a != '!')
    {
        ElemType b ;
        cin >> b;
        ElemType e = (ElemType)b - 48;
        a = b;
        if(a != '!')
            cout << ListInsert(L,p,b)<<endl;
        p++;
    }
 return "OK";
}
    
string FillListWithNum(LinkList &L,int i){
    
    int e;
    
    for(int j =1;j<=i;j++){
        cin >> e;
        ListInsert(L,j,e);
    }
 return "OK";
}
//     ShowList(L);

// DeleteList(L,2);
// ShowList(L);
//     return 0;
// }

 

 

#include<iostream>
#include"LinkList.h"
using namespace std;

/*
 逆转链表结点链接方向

*/

int main(){

    LinkList LA;
    LinkList LB;

    InitList(LA);
    InitList(LB);

    FillListWithNum(LA,4);

    LNode *pa = LA->next;
    
    LNode *pb;

    int n=1;

    while(pa->next){
        ++n;
        pa=pa->next;
    }
  
    LB->next=pa;
    pb = pa;

    for(n;n>=1;n--){
        
        pb->next=GetElement(LA,n);
        pb=pb->next;
    }

    pb->next=NULL;

    //delete LA;

        //cout<<endl;
        ShowList(LB);
        
        system("pause");
        return 0;
    }

 

posted @ 2020-11-17 22:46  倔强的不死人  阅读(356)  评论(0编辑  收藏  举报