实现单链表的倒置

前提:链表结点结构体:

typedef struct node
{
    ElemType data;
    node *next;
}Node;

1、最初设想:定义三个Node指针:pos、pre、the_next  分别指向当前结点、当前结点的上一个结点、当前结点的下一个结点

Node* convert(Node *head)
{
    Node *pos,*pre,*the_next;
    pos=head;
    pre=NULL;
    the_next=pos->next;
    while(pos!=NULL)
    {
        if(pre==NULL)        //当前结点为头结点的情况
        {
            pos->next=NULL;
        }
        else
        {
            pos->next=pre;
        }
        pre=pos;
        pos=the_next;
        the_next=pos->next;      //出错的地方  
    }
    head=pre;
    return head;
}

上面的代码有个错误:每次while循环判定时,指针位置都是:

,这样的话,在pos==NULL时,对the_next还有赋值操作:the_next=pos->next,导致出错

另外,上面代码对于头结点的处理也显得很繁琐

2、修改后的代码:定义pos、pre、back 三个指针分别指向当前结点、上一个结点和用于备份下一个结点

Node* convert(Node *head)
{
    Node *pos,*pre,*back;   //pos指向当前结点,pre指向上一个结点,back指向当前节点的next结点,作为备份

    /*先判断链表是否需要倒置*/
    if(head==NULL||head->next==NULL)
    {
        return head;
    }

    pre=head;
    pos=head->next;    //这步之前要做链表是否为空的判定
    while(pos!=NULL)
    {
        back=pos->next;     //备份
        pos->next=pre;

        /*向下移动一个位置*/
        pre=pos;
        pos=back;
    }
    head->next=NULL;    //将原来头结点的next指向NULL
    head=pre;
    return head;
}

这样在每次while判定的时候,指针位置为

,这样就解决了前面指针的问题了

原文地址:https://www.cnblogs.com/xmkk/p/3288834.html