美文网首页
链表反转

链表反转

作者: 陈_振 | 来源:发表于2018-09-12 21:52 被阅读0次
struct Node* reverseList(struct Node *head) {
    struct Node *p = head;
    
    // 反转后的链表头部
    struct Node *newListHead = NULL;
    
    // 遍历链表
    while (p != NULL) {
        // 记录下一个结点
        struct Node *temp = p->next;
        
        // 使用头插法
        // 当前结点的next指向新链表的头部
        p->next = newListHead;
        
        // 更新链表头部为当前结点
        newListHead = p;
        
        // 移动P
        p = temp;
    }
    
    return newListHead;
}

struct Node* constructList(void) {
    // 头结点
    struct Node *head = NULL;
    // 尾结点
    struct Node *tail = NULL;
    
    for (int i = 0; i < 5; i++) {
        struct Node *node = (struct Node *)malloc(sizeof(struct Node));
        node->data = I;
        
        if (head == NULL) {
            head = node;
        } else {
            tail->next = node;
        }
        
        tail = node;
    }
    
    tail->next = NULL;
    
    return head;
}

void printList(struct Node *head) {
    struct Node *temp = head;
    while (temp != NULL) {
        printf("node is %d\n", temp->data);
        temp = temp->next;
    }
}
屏幕快照 2018-09-12 下午9.52.29.png

相关文章

  • Algorithm小白入门 -- 单链表

    单链表递归反转链表k个一组反转链表回文链表 1. 递归反转链表 单链表节点的结构如下: 1.1 递归反转整个单链表...

  • 链表反转

    循环反转链表 递归反转链表

  • 5个链表的常见操作

    链表 链表反转 LeetCode206:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 环路检...

  • JZ-015-反转链表

    反转链表 题目描述 输入一个链表,反转链表后,输出新链表的表头。题目链接: 反转链表[https://www.no...

  • 算法学习(链表相关问题)

    LeetCode 206 反转链表 LeetCode 92 反转链表II (练习) 完成,方法:在反转链表上改 L...

  • 实战高频leetcode题目

    1. 反转链表 : 反转链表是常见简单题目,定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点...

  • 【教3妹学算法】2道链表类题目

    题目1:反转链表 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 示例 1: 输入:head ...

  • leecode刷题(22)-- 反转链表

    leecode刷题(22)-- 反转链表 反转数组 反转一个单链表。 示例: 进阶:你可以迭代或递归地反转链表。你...

  • 链表简单算法相关练习

    单链表反转: 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。 迭代方式实现: 复杂度分析: 时...

  • iOS之【链表】

    构建链表 链表反转

网友评论

      本文标题:链表反转

      本文链接:https://www.haomeiwen.com/subject/bdabgftx.html