码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构与算法分析 3.12 — 单链表转置

时间:2015-01-09 22:08:37      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

题目一:  不含头结点的单链表转置,算法时间复杂度O(N)

代码如下

struct LNode;
typedef struct LNode *List;
typedef struct LNode *Position;
struct LNode
{
    ElementType elem;
    Position next;
};

/* 无头结点单链表转置 */
List Reversion(List L)
{
    Position previousPos, currentPos, nextPos;

    previousPos = nullptr;
    currentPos = L;
    nextPos = L->next;

    while (nextPos != nullptr)
    {
        currentPos->next = previousPos;
        previousPos = currentPos;
        currentPos = nextPos;
        nextPos = nextPos->next;
    }
    currentPos->next = previousPos;
    return currentPos;
}

 

题目二: 带头结点的单链表转置,算法时间复杂度O(N)

struct LNode;
typedef struct LNode *List;
typedef struct LNode *Position;
struct LNode
{
    ElementType elem;
    Position next;
};

/* 带头结点单链表转置 */
List Reversion(List list)
{
    List header = list;
    List currentPos = header->next;

    header->next = nullptr;
    while (currentPos != nullptr)
    {
        Position tmp = currentPos;
        currentPos = currentPos->next;
        tmp->next = header->next;
        header->next = tmp;
    }
    return header;
}

 

数据结构与算法分析 3.12 — 单链表转置

标签:

原文地址:http://www.cnblogs.com/tallisHe/p/4214197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!