单链表反转

typedef struct ListNode
{
    int data;
    ListNode *pNext;

    ListNode(int data)
    {
        this->data = data;
        pNext = NULL;
    }
} *PListNode;

PListNode reverseList(PListNode head)
{
    if (head == NULL || head->pNext == NULL) {
        return head;
    }

    PListNode curNode = head;
    PListNode nextNode = head->pNext;
        //注意这里一定要写成nextNode != NULL,而不要写成curNode->pNext!= NULL,
    while (nextNode != NULL)
    {
        PListNode pTemp = nextNode->pNext;
        nextNode->pNext = curNode;
        curNode = nextNode;
        nextNode = pTemp;
    }
    head->pNext = NULL;  //翻转完成后将原来的第一个节点的pNext指针赋值为NULL,会死循环的
    return curNode; 
}

void printList(PListNode head)
{
    PListNode node = head;
    while (node != NULL)
    {
        cout << node->data << " ";
        node = node->pNext;
    }
    cout << endl;
}

void main() {
    int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    PListNode head = new ListNode(0);
    PListNode next = head;
    for (int i = 1; i < 10; i++)
    {
        PListNode node = new ListNode(i);
        next->pNext = node;
        next = node;
    }

    cout << "链表反转前" << endl;
    printList(head);

    head = reverseList(head);

    cout << "链表反转后" << endl;
    printList(head);

    getchar();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 链表结构 递归和非递归实现都基于下面这张图的原理,不同的是,递归时从后向前,非递归是从前向后,并且非递归要head...
    alonwang阅读 251评论 0 1
  • 数组中a[i] 与 a[j] 如果需要调换位置,我们通常会定义一个中间变量来暂时存放变量,这是一个思想: 这样我们...
    白马王朗阅读 272评论 0 1
  • 单链表反转 单链表初始化 输出 反转 释放 实现代码 尚未实现 元素插入 元素删除
    dawter阅读 267评论 0 0
  • 基本问题 如何将单链表反转? 单链表结构定义 算法实现 进阶问题 如何将单链表在指定区间内进行反转? 问题分析 这...
    craneyuan阅读 560评论 0 5
  • 最近与人瞎聊,聊到各大厂的面试题,其中有一个就是用java实现单链表反转。闲来无事,决定就这个问题进行一番尝试。 ...
    冬天里的懒喵阅读 4,191评论 1 14

友情链接更多精彩内容