/*单链表的操作:逆置法*/
/*
* SCs in different methods
* author: Whywait
*/
typedef struct node {
Elemtype data;
struct node* next;
} Lnode;
/*Method One*/
/*
* 三兄弟列队走
*/
Lnode* reverseSList(Linklist& L) {
// this is a singly linked list with a head node
// and I name the three brothers: one, two, three
// but we need to face the special situation: there is less than 3 nodes in the list
// so let's talk about it first
Lnode* one, * two, * three;
if (!L->next || !L->next->next) return L; // if there is one node or none, do nothing
one = L->next;
two = one->next;
one->next = NULL;
if (!two->next) { // if three are two nodes
tow->next = one;
L->next = two;
return L;
}
three = two->next;
while (three) { // if three are three or more than three nodes
// three brothers go along the slist until the THREE brother is NULL
two->next = one;
one = two;
two = three;
three = three->next;
}
L->next = two;
return L;
}
链表必学算法(五):逆置法
最新推荐文章于 2024-04-15 23:01:14 发布
本文介绍了一种单链表的逆置算法,通过三兄弟指针技巧实现链表节点的逆序连接。首先处理特殊情形,如链表为空或只有一个节点的情况。接着,通过迭代方式,使三个指针沿着链表前进,完成逆置操作。
608

被折叠的 条评论
为什么被折叠?



