c语言链表示例_示例说明的数据结构-链表

c语言链表示例

Just like a garland is made with flowers, a linked list is made up of nodes. We call every flower on this particular garland to be a node. And each of the node points to the next node in this list as well as it has data (here it is type of flower).

就像用花制成的花环一样,链表由节点组成。 我们称此特殊花环上的每朵花为节点。 每个节点都指向该列表中的下一个节点,并且每个节点都有数据(这里是花朵的类型)。

种类 (Types)

单链表 (Singly Linked List)

Singly linked lists contain nodes which have a data field as well as a next field, which points to the next node in the sequence. Operations that can be performed on singly linked lists are insertion, deletion and traversal.

单链接列表包含具有data字段以及指向字段中下一个节点的next字段的节点。 可以在单链接列表上执行的操作是插入,删除和遍历。

head
    |
    |
  +-----+--+      +-----+--+      +-----+------+
  |  1  |o----->  |  2  |o----->  |  3  | NULL |
  +-----+--+      +-----+--+      +-----+------+

Internal implementation of CPython, the frames and evaluated variables are kept on a stack.

CPython的内部实现,框架和评估变量保存在堆栈中。

For this we need to iterate only forward aur get the head, therefore singly linked-list is used.

为此,我们只需要迭代前向aur获得头部,因此使用单链表。

双链表 (Doubly Linked List)

Doubly linked lists contain node which have data field, next field and another link field prev pointing to the previous node in the sequence.

双链列表包含的节点具有data字段, next字段和另一个链接字段prev指向序列中的上一个节点。

head
           |
           |
  +------+-----+--+    +--+-----+--+       +-----+------+
  |      |     |o------>  |     |o------>  |     |      |
  | NULL |  1  |          |  2  |          |  3  | NULL |
  |      |     |  <------o|     |  <------o|     |      |
  +------+-----+--+    +--+-----+--+       +-----+------+

The browser cache which allows you to hit the BACK and FORWARD button. Here we need to maintain a doubly linked list, with URLs as data field, to allow access in both direction. To go to previous URL we will use prev field and to go to next page we will use next field.

浏览器缓存,可让您单击“后退”和“前进”按钮。 在这里,我们需要维护一个以URLs为数据字段的双向链接列表,以允许双向访问。 要转到上一个URL,我们将使用prev字段,而转到下一页,我们将使用next字段。

通报链表 (Circular Linked List)

Circular linked lists is a singly linked list in which last node, next field points to first node in the sequence.

循环链表是单链表,其中最后一个节点, next字段指向序列中的第一个节点。

head
      |
      |
    +-----+--+      +-----+--+      +-----+--+
    —> | 1 |o-----> | 2 |o----->    | 3 |o----| 
    +-----+--+      +-----+--+      +-----+--+

Timesharing problem solved by the operating system.

分时问题由操作系统解决。

In a timesharing environment, the operating system must maintain a list of present users and must alternately allow each user to use a small portion of CPU time, one user at a time. The operating system will pick a user, let him/her use a small amount of CPU time and then move on to the next user.

在分时环境中,操作系统必须维护一个当前用户列表,并且必须交替允许每个用户使用一小部分CPU时间,一次只能使用一个用户。 操作系统将选择一个用户,让他/她使用少量的CPU时间,然后转移到下一个用户。

For this application, there should be no NULL pointers unless there is absolutely no one requesting CPU time, i.e list is empty.

对于此应用程序,除非绝对没有人请求CPU时间(即列表为空),否则不应有NULL指针。

基本操作 (Basic Operations)

插入 (Insertion)

To add a new element to the list.

向列表添加新元素。

Insertion at the beginning:

在开始时插入:

  • Create a new node with given data.

    使用给定的数据创建一个新节点。
  • Point new node’s next to old head.

    点新节点的nexthead

  • Point head to this new node.

    head指向该新节点。

Insertion in the middle/end.

插入中间/末端。

Insertion after node X.

在节点X之后插入。

  • Create a new node with given data.

    使用给定的数据创建一个新节点。
  • Point new node’s next to old X’s next.

    将新节点的next指向旧X的next

  • Point X’s next to this new node.

    点X在此新节点next

Time Complexity: O(1)

时间复杂度:O(1)

删除中 (Deletion)

To delete existing element from the list.

从列表中删除现有元素。

Deletion at the beginning

开始删除

  • Get the node pointed by head as Temp.

    得到head指向的节点为Temp。

  • Point head to Temp’s next.

    head指向Temp的next

  • Free memory used by Temp node.

    Temp节点使用的可用内存。

Deletion in the middle/end.

在中间/末端删除。

Deletion after node X.

在节点X之后删除。

  • Get the node pointed by X as Temp.

    X指向的节点作为Temp。

  • Point X’s next to Temp’s next.

    点X的next是Temp的next

  • Free memory used by Temp node.

    Temp节点使用的可用内存。

Time Complexity: O(1)

时间复杂度:O(1)

遍历 (Traversing)

To travel across the list.

遍历列表。

Traversal

遍历

  • Get the node pointed by head as Current.

    head指向的节点作为Current。

  • Check if Current is not null and display it.

    检查Current是否不为null并显示它。
  • Point Current to Current’s next and move to above step.

    将“当前”指向“当前”的next然后移至上一步。

Time Complexity: O(n) // Here n is size of link-list

时间复杂度:O(n)//这里n是链接列表的大小

实作 (Implementation)

单链表的C ++实现 (C++ implementation of singly linked list)

// Header files
#include <iostream>

struct node
{
    int data;
    struct node *next;
};

// Head pointer always points to first element of the linked list
struct node *head = NULL;
在每个节点中打印数据 (Printing data in each node)
// Display the list
void printList()
{
    struct node *ptr = head;

    // Start from the beginning
while(ptr != NULL)
{
    std::cout << ptr->data << " ";
    ptr = ptr->next;
}

std::cout << std::endl;
}
开始插入 (Insertion at the beginning)
// Insert link at the beginning
void insertFirst(int data)
{
    // Create a new node
    struct node *new_node = new struct node;

    new_node->data = data;

// Point it to old head
new_node->next = head;

// Point head to new node
head = new_node;

std::cout << "Inserted successfully" << std::endl;
}
开始删除 (Deletion at the beginning)
// Delete first item
void deleteFirst()
{
    // Save reference to head
    struct node *temp = head;

    // Point head to head's next
head = head->next;

// Free memory used by temp
temp = NULL:
delete temp;

std::cout << "Deleted successfully" << std::endl;
}
尺寸 (Size)
// Find no. of nodes in link list
void size()
{
    int length = 0;
    struct node *current;

    for(current = head; current != NULL; current = current->next)
{
    length++;
}

std::cout << "Size of Linked List is " << length << std::endl;
}
正在搜寻 (Searching)
// Find node with given data
void find(int data){

    // Start from the head
struct node* current = head;

// If list is empty
if(head == NULL)
{
    std::cout << "List is empty" << std::endl;
    return;
}

// Traverse through list
while(current->data != data){

    // If it is last node
    if(current->next == NULL){
        std::cout << "Not Found" << std::endl;
        return;
    }
    else{
        // Go to next node
        current = current->next;
    }
}

// If data found
std::cout << "Found" << std::endl;
}
节点后删除 (Deletion after a node)
// Delete a node with given data
void del(int data){

    // Start from the first node
struct node* current = head;
struct node* previous = NULL;

// If list is empty
if(head == NULL){
    std::cout << "List is empty" << std::endl;
    return ;
}

// Navigate through list
while(current->data != data){

    // If it is last node
    if(current->next == NULL){
        std::cout << "Element not found" << std::endl;
        return ;
    }
    else {
        // Store reference to current node
        previous = current;
        // Move to next node
        current = current->next;
    }

}

// Found a match, update the node
if(current == head) {
    // Change head to point to next node
    head = head->next;
}
else {
    // Skip the current node
    previous->next = current->next;
}

// Free space used by deleted node
current = NULL;
delete current;
std::cout << "Deleted succesfully" << std::endl;
}

单链表的Python实现 (Python Implementation of Singly Linked List)

class Node(object):
    # Constructor
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next

    # Function to get data
def get_data(self):
    return self.data

# Function to get next node
def get_next(self):
    return self.next

# Function to set next field
def set_next(self, new_next):
    self.next = new_next
class LinkedList(object):
    def __init__(self, head=None):
        self.head = head
插入 (Insertion)
# Function to insert data
def insert(self, data):
    # new_node is a object of class Node
    new_node = Node(data)
    new_node.set_next(self.head)
    self.head = new_node
    print("Node with data " + str(data) + " is created succesfully")
尺寸 (Size)
# Function to get size
def size(self):
    current = self.head
    count = 0
    while current:
        count += 1
        current = current.get_next()
    print("Size of link list is " + str(count))
正在搜寻 (Searching)
# Function to search a data
def search(self, data):
    current = self.head
    found = False
    while current and found is False:
        if current.get_data() == data:
            found = True
        else:
            current = current.get_next()
    if current is None:
        print("Node with data " + str(data) + " is not present")
    else:
        print("Node with data " + str(data) + " is found")
节点后删除 (Deletion after a node)
# Function to delete a node with data
def delete(self, data):
    current = self.head
    previous = None
    found = False
    while current and found is False:
        if current.get_data() == data:
            found = True
        else:
            previous = current
            current = current.get_next()
    if current is None:
        print("Node with data " + str(data) + " is not in list")
    elif previous is None:
        self.head = current.get_next()
        print("Node with data " + str(data) + " is deleted successfully")
    else:
        previous.set_next(current.get_next())
        print("Node with data " + str(data) + " is deleted successfully")

Advantages

优点

  1. Linked lists are a dynamic data structure, which can grow and shrink, allocating and deallocating memory while the program is running.

    链接列表是一个动态数据结构,可以在程序运行时增长和收缩,分配和取消分配内存。
  2. Insertion and deletion of node are easily implemented in a linked list at any position.

    节点的插入和删除可以在任何位置的链表中轻松实现。

Disadvantages

缺点

  1. They use more memory than arrays because of the memory used by their pointers (next and prev).

    由于它们的指针( nextprev )使用了内存,因此它们比数组使用更多的内存。

  2. Random access is not possible in linked list. We have to access nodes sequentially.

    链表中不能随机访问。 我们必须顺序访问节点。
  3. It’s more complex than array. If a language supports array bound check automatically, Arrays would serve you better.

    它比数组更复杂。 如果一种语言自动支持数组绑定检查,那么数组会更好地为您服务。
注意 (Note)

We have to use free() in C and delete in C++ to free the space used by deleted node, whereas, in Python and Java free space is collected automatically by garbage collector.

我们必须在C中使用free()并在C ++中删除以释放已删除节点使用的空间,而在Python和Java中,垃圾收集器会自动收集可用空间。

翻译自: https://www.freecodecamp.org/news/data-structures-explained-with-examples-linked-list/

c语言链表示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值