数据结构:链表反转

题外话:工作2年第一次写链表反转emmm,刷的题还是不够TT
开始正题!
思路:
1)如果链表为空或者只有一个节点,那肯定就不需要做反转操作啦;
2)借助p1和p2两个指针对链表进行遍历,每次将p2->next指向前面的p1;
3)遍历的条件是p1和p2都不是空指针,所以遍历结束后p1就是新的首节点;
4)最后不要忘记尾结点和它的next指向空指针。
画了简单的流程图:
链表反转
上代码:
(完整代码见https://blog.csdn.net/SanShuiGeGe/article/details/124067370)

/* 节点结构,next指针和T类型数据 */
template<typename T>
class Node{
public:
    T ele;
    Node *next;
    Node(){next=nullptr;}
};
/* 无头节点的单向链表 */
template<typename T>
class SingleList{
private:
    Node<T> *m_nodeHead;//首节点
    Node<T> *m_nodeTail;//尾结点
}
template<typename T>
void SingleList<T>:: reverse(void)
{
    Node<T> *p0 = nullptr;
    Node<T> *p1 = nullptr;
    Node<T> *p2 = nullptr;
    if(m_nodeHead == m_nodeTail)
    {
        return;
    }
    p1 = m_nodeHead;
    p2 = m_nodeHead->next;
    m_nodeTail = p1;
    m_nodeTail->next = nullptr;
    while(p1 != nullptr && p2 != nullptr)
    {
        p0 = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = p0;
    }
    m_nodeHead = p1;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
双链表的反转可以通过修改节点的前驱和后继指针来实现。以下是一个示例代码实现: ```c #include <stdio.h> #include <stdlib.h> // 定义双链表节点 struct Node { int data; struct Node* prev; struct Node* next; }; // 反转双链表 struct Node* reverse(struct Node* head) { struct Node* current = head; struct Node* temp = NULL; while (current != NULL) { // 交换当前节点的前驱和后继指针 temp = current->prev; current->prev = current->next; current->next = temp; // 向后移动 current = current->prev; } // 更新头节点指针 if (temp != NULL) { head = temp->prev; } return head; } // 打印双链表 void printList(struct Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } } int main() { // 创建双链表 struct Node* head = (struct Node*)malloc(sizeof(struct Node)); struct Node* second = (struct Node*)malloc(sizeof(struct Node)); struct Node* third = (struct Node*)malloc(sizeof(struct Node)); head->data = 1; head->prev = NULL; head->next = second; second->data = 2; second->prev = head; second->next = third; third->data = 3; third->prev = second; third->next = NULL; printf("原始双链表:"); printList(head); // 反转双链表 head = reverse(head); printf("\n反转后的双链表:"); printList(head); return 0; } ``` 这段代码首先定义了一个 `Node` 结构体来表示双链表的节点,其中包括一个数据域 `data`、一个指向前驱节点的指针 `prev`,以及一个指向后继节点的指针 `next`。 在 `reverse` 函数中,我们使用一个临时变量 `temp` 来交换当前节点的前驱和后继指针,然后将当前节点指针向后移动。反转完成后,更新头节点指针,确保它指向反转后的链表的头部。 最后,在 `main` 函数中创建一个简单的双链表,并调用 `reverse` 函数进行反转操作。通过调用 `printList` 函数来打印原始链表和反转后的链表。 以上代码的输出结果应为: ``` 原始双链表:1 2 3 反转后的双链表:3 2 1 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值