题目一: 不含头结点的单链表转置,算法时间复杂度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; }
时间: 2024-10-16 22:22:07