逆转链表的实现

#include <iostream>
using namespace std;

typedef struct _List_my
{
    int index;
    struct _List_my *next;
    _List_my(int i):index(i), next(NULL){}
    _List_my():next(NULL) {}
}MyList;

MyList* head = 0;

MyList* InitList(int size)
{
    head = new MyList();
    MyList* tmp, *curr;
    curr = head;
    for(int i=0; i<size; i++)
    {
        tmp = new MyList(i);
        if(!tmp)
            return 0;
        curr->next = tmp;
        curr = curr->next;
    }

    return head;
}

int print_list(MyList* first)
{
    MyList *temp = first;
    if(!temp)
        return -1;
    while((temp = temp->next))
    {
        cout<<temp->index<<endl;
    }
    return 0;
}

int free_list(MyList* first)
{
    MyList* tmp = first;
    MyList* del;
    int i = 0;
    if(!first)
        return -1;
    while(tmp->next != 0)
    {
        del = tmp->next;
        first->next = del->next;
        delete del;
        cout<<"删除第"<<++i<<"个结点"<<endl;
    }
    delete tmp;
    cout<<"删除头结点"<<endl;
    return 0;

}

// 以第一个节点为中心点,从第2个结点开始处理逐个翻转到第一个节点左边
// 第一个节点变成最后一个结点,最后一个结点变成第一个节点。
MyList* reserve_list(MyList* first)
{
    MyList* pre = first->next;
    MyList* curr = first->next->next;
    MyList* loc = 0;
    if(!first || !pre)
        return 0;

    pre->next = 0;
   
    while(curr)
    {
        loc = curr->next; // 保存下一次赋给curr的地址
        curr->next = pre; 
        pre = curr;
        curr = loc;      // 赋给curr,不能用curr=curr->next,因为此时curr->next=pre了。
    }
    first->next = pre; // 这一句容易出错!!!不能用first->next = curr
                       // 因为跳出循环的时候curr为0了!
    return first;
}
// 从最后一个节点开始往前逐个插在第一个节点之前
MyList* reserve_list(MyList * first)
{
    if(!first)
        return 0;
    MyList* loc = first->next; //第一个节点翻转后变成最后一个结点
    MyList* curr = loc;        //每次循环的起点
    MyList* pre = curr;
    MyList* tmp = first;       //保存插入点之前的位置
    while(loc->next != 0)
    {
        while(curr->next != 0)
        {
            pre = curr;
            curr = curr->next;
        }
        pre->next = 0;
        curr->next = tmp->next;
        tmp->next = curr;
   
        tmp = curr;
        curr = loc;       
    }
    return first;
}

int main()
{
    MyList* first = InitList(100);
    print_list(first);
    MyList* rfst = reserve_list(first);
    print_list(rfst);
    free_list(rfst);
    return 0;
}

原文地址:https://www.cnblogs.com/kex1n/p/2286572.html