链表逆序算法

问题:

给定一个链表,请将其逆序。即如果链表原来为1->2->3->4->5->null,逆序后为5->4->3->2->1->null.

解法1:迭代算法

迭代算法效率较高,但是代码比递归算法略长。递归算法虽然代码量更少,但是难度也稍大,不细心容易写错。 迭代算法的思想就是遍历链表,改变链表节点next指向,遍历完成,链表逆序也就完成了。代码如下:

struct node {
    int data;
    struct node* next;
};
typedef struct node* pNode;
pNode reverse(pNode head)
{
    pNode current = head;
    pNode next = NULL, result = NULL;
    while (current != NULL) {
        next = current->next;
        current->next = result;
        result = current;
        current = next;
    }
    return result;
}

如果不返回值,可以传递参数改为指针的指针,直接修改链表的头结点值(如果在C++中直接传递引用更方便),可以写出下面的代码:

void reverse2(struct node** headRef)
{   
    pNode current = *headRef;
    pNode next = NULL, result = NULL;
    while (current != NULL) {
        next = current->next;
        current->next = result;
        result = current;
        current = next;
    }
    *headRef = result;
}

解法2:递归算法

递归算法实现原理:假定原链表为1,2,3,4,则先逆序后面的2,3,4变为4,3,2,然后将节点1链接到已经逆序的4,3,2后面,形成4,3,2,1,完成整个链表的逆序。代码如下:

void reverseRecur(struct node** headRef)
{
    if (*headRef == NULL)  return;
    pNode first, rest;
    first = *headRef;       //假定first={1,2,3,4}
    rest = first->next;   // rest={2,3,4}
    if (rest == NULL) return;
    reverseRecur(&rest); //rest逆序后变成{4,3,2}
    first->next->next = first; //将第一个节点置于逆序后链表最后
    first->next = NULL;
    *headRef = rest;  //更新头结点
}

如果使用C++的引用类型,代码会稍显简单点,代码如下:

void reverseRecur(pNode& p)
{
if (!p) return;
 pNode rest = p->next;
  if (!rest) return;
  reverseRecur(rest);
  p->next->next = p;
  p->next = NULL;
  p = rest;
}
    原文作者:石锅拌饭
    原文地址: https://blog.csdn.net/sgbfblog/article/details/7754103
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞