数据结构-单向链表

c/c++

浏览数:38

2019-6-29

单向列表节点

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

单链表创建 反转链表 删除节点

         //创建节点
        LinkNode *rootNode = malloc(sizeof(LinkNode));
        rootNode->data = 1;
        rootNode->next = NULL;
        
        LinkNode *node1 = malloc(sizeof(LinkNode));
        node1->data = 2;
        node1->next = NULL;
        
        LinkNode *node2 = malloc(sizeof(LinkNode));
        node2->data = 3;
        node2->next = NULL;
        
        //生成链表
        rootNode->next = node1;
        node1->next = node2;
        
        //反转链表
        LinkNode *node = reverseLink(rootNode);
        
        //删除链表中的值为3元素
        deleteLinkElement(node, 2);

反转链表

        LinkNode* reverseLink(LinkNode *node){
            if (node == NULL) {return NULL;}
            LinkNode *pre = NULL;
            while (node) {
                LinkNode *nextTemp = node->next;
                node->next = pre;
                pre = node;
                node = nextTemp;
            }
            return pre;
        }

删除链表节点

        LinkNode* deleteLinkElement(LinkNode *node, int element) {
            if (node == NULL) {return NULL;}
            LinkNode *pre = NULL;
            
            while (node) {
                LinkNode *nextTemp = node->next;
                if (node->data == element) {
                    if (pre) {
                        pre->next = nextTemp;
                    } else {
                        *node = *nextTemp;
                    }
                }
                pre = node;
                node = nextTemp;
            }
            return pre;
        }

作者:彭怀杰