线性表的链式表示和实现

线性列表的链式表示(也称为链接表示)是使用节点实现的,其中每个节点都包含数据元素和指向列表中下一个节点的指针。下面是 C 语言中线性列表的链式表示和实现示例:

 

'''c

 

#include

#include

 

struct Node {

    int data;

    struct Node* next;

};

 

// Function to create a new node

struct Node* createNode(int data) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = data;

    newNode->next = NULL;

    return newNode;

}

 

// Function to insert an element at the beginning of the list

struct Node* insertAtBeginning(struct Node* head, int data) {

    struct Node* newNode = createNode(data);

 

    if (head == NULL) {

        return newNode;

    }

 

    newNode->next = head;

    return newNode;

}

 

// Function to insert an element at the end of the list

struct Node* insertAtEnd(struct Node* head, int data) {

    struct Node* newNode = createNode(data);

 

    if (head == NULL) {

        return newNode;

    }

 

    struct Node* current = head;

    while (current->next != NULL) {

        current = current->next;

    }

 

    current->next = newNode;

    return head;

}

 

// Function to display the elements of the list

void displayList(struct Node* head) {

    struct Node* current = head;

 

    while (current != NULL) {

        printf("%d ", current->data);

        current = current->next;

    }

 

    printf("\n");

}

 

int main() {

    struct Node* head = NULL;

 

    head = insertAtBeginning(head, 3);

    head = insertAtEnd(head, 5);

    head = insertAtEnd(head, 7);

 

    displayList(head);

 

    return 0;

}

 

'''

 

在此实现中,“struct Node”用于表示列表中的每个节点。“createNode”函数负责创建一个新节点并初始化其数据和下一个指针。“insertAtBeginning”函数通过更新新节点的下一个指针以指向当前头,并将新节点作为新头返回,在列表的开头插入一个新节点。“insertAtEnd”函数通过遍历列表直到到达最后一个节点,然后更新最后一个节点的下一个指针以指向新节点,在列表末尾插入一个新节点。'displayList' 函数遍历列表并打印每个节点的数据。

 

在“main”函数中,我们创建一个空列表,然后使用“insertAtBeginning”和“insertAtEnd”函数在列表的开头和结尾插入元素。最后,我们使用“displayList”函数来打印列表的元素。根据对线性列表的链式实现的要求修改和扩展此代码。

 

你可能感兴趣的:(C语言专栏,开发语言,c语言,数据结构,算法)