单链表反转的迭代和递归解法

单链表反转的迭代和递归解法

迭代

  1. 定义三个指针pnow,pre,pnex;
  2. pnow指向head,pre,pnex指向空(把pre定义为空的好处,不用把头结点特殊处理)
  3. 循环体内:
    1、把pnex指向pnow的next
    2、判断是否为空,若为空则pnow为尾结点(只为了标记尾结点)
    3、反转指针: pnow->next = pre;
    4、后移指针: pre = pnow;pnow = pnext;
    5、当pnow指向NULL时,退出循环,并返回尾结点
Node * reverseList(List head){
    Node *pnow = head;
    Node *pre = NULL;
    Node *pnext = NULL;
    //定义用来标记尾指针
    Node *tail = NULL;
    while(pnow != NULL){
        pnext = pnow->next;
        if(pnext == NULL){
            tail = pnow;
        }
        pnow->next = pre;
        pre = pnow;
        pnow = pnext;
    }
    return tail;
}

递归

Node * reverseList(List head)
{
    //如果链表为空或者链表中只有一个元素
    if(head == NULL || head->next == NULL)
    {
        return head;
    }
    else
    {
        //先反转后面的链表,走到链表的末端结点
        Node *newhead = reverseList(head->next);
        //再将当前节点设置为后面节点的后续节点
        head->next->next = head;
        head->next = NULL;
        
        return newhead;
    }
}

感谢博主dashuai,原博:
[1]:https://www.cnblogs.com/kubixuesheng/p/4394509.html

你可能感兴趣的:(算法)