zoukankan      html  css  js  c++  java
  • 秒懂单链表及其反转(reverse)

    什么是链表,这种数据结构是由一组Node组成的,这群Node一起表示了一个序列。链表是最普通,最简单的数据结构(物理地址不连续),它是实现其他数据结构如stack, queue等的基础

    链表比起数组来,更易于插入,删除。

    Node可以定义如下:

    typedef int element_type;  
    typedef struct node *node_ptr;  
      
    struct node {  
    element_type element;  
    node_ptr next;  
    }; 
     

    另外关于要不要头节点这个问题,我建议加上头节点,理由如下:

    1. 没有头节点,删除第一个节点后,不小心就丢失了List
    2. 插入头部时,没有个直观的方法。
    3. 通常的删除操作,都要先找到前一个节点,如果没有头节点,删除第一个节点就不一样了。

    接下来重点实现单链表的反转,这也是常常考到的一个问题,下面是C语言实现:

    void list_reverse(LIST L)  
    {  
        if (L->next == NULL) return;  
        node_ptr p = L->next, first = L->next;  
        while (p != NULL && p->next != NULL) {  
            node_ptr next_node = p->next;  
            p->next = next_node->next;  
            next_node->next = first;  
            first = next_node;  
        }  
        L->next = first;  
    }  
     

     --

  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/Ph-one/p/6764338.html
Copyright © 2011-2022 走看看