【链表】

#include <stdio.h>
#include <stdlib.h>

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

struct Node* createList(){
    struct Node* headNode = (struct Node*)malloc(sizeof(struct Node));
    headNode->next = NULL;
    return headNode;
}

struct Node* createNode(int data) {
    struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
    newnode->data = data;
    newnode->next = NULL;
    return newnode;
}

void printList(struct Node* headNode) {
    struct Node* pMove = headNode->next;
    while (pMove) {
        printf("%d", pMove->data);
        pMove = pMove->next;
    }
    printf("\n");
}

void insertNodeByHead(struct Node* headNode, int data) {
    struct Node* newNode = createNode(data);
    newNode->next = headNode->next;
    headNode->next = newNode;

}

void deleteNodeByAppoint(struct Node* headNode, int posData) {
    struct Node* posNode = headNode->next;
    struct Node* posNodeFront = headNode;
    if (posNode == NULL) {
        printf("无法删除,链表为空!\n");
    }
    else {
        while (posNode->data != posData) {
            posNodeFront = posNode;
            posNode = posNodeFront->next;
            if (posNode == NULL) {
                printf("没有找到指定位置的数据,不能删除!\n");
            }
        }
        posNodeFront->next = posNode->next;
        free(posNode);
    }

}

int main() {
    struct Node* list = createList();
    insertNodeByHead(list, 1);
    insertNodeByHead(list, 2);
    insertNodeByHead(list, 3);
    printList(list);

    deleteNodeByAppoint(list, 2);
    printList(list);
    system("pause");
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容