1 /**
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/queue.h>
19 #include "test.h"
20 #include "functionalext.h"
21
22 #define NODE_TEN 10
23 #define NODE_TWENTY 20
24 #define NODE_THIRTY 30
25
26 // 定义链表节点结构
27 struct Node {
28 int data;
29 LIST_ENTRY(Node) entries;
30 };
31
32 // 定义链表头结构
33 LIST_HEAD(Head, Node) head = LIST_HEAD_INITIALIZER(head);
34
35 // 插入节点到链表
insert_node(int data)36 void insert_node(int data)
37 {
38 struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
39 EXPECT_PTRNE("insert_node", new_node, NULL);
40 new_node->data = data;
41 LIST_INSERT_HEAD(&head, new_node, entries);
42 }
43
44 // 删除节点
delete_node(int data)45 void delete_node(int data)
46 {
47 struct Node *node;
48 LIST_FOREACH(node, &head, entries) {
49 if (node->data == data) {
50 LIST_REMOVE(node, entries);
51 free(node);
52 return;
53 }
54 }
55 }
56
57 // 遍历链表并返回所有节点值的字符串
traverse_list(char * result,size_t result_len)58 void traverse_list(char *result, size_t result_len)
59 {
60 struct Node *node;
61 char buffer[20];
62 size_t pos = 0;
63 LIST_FOREACH(node, &head, entries) {
64 int res = snprintf(buffer, sizeof(buffer), "%d ", node->data);
65 EXPECT_GTE("traverse_list -> snprintf", res, 0);
66 size_t len = strlen(buffer);
67 if (pos + len < result_len) {
68 strcpy(result + pos, buffer);
69 pos += len;
70 }
71 }
72 }
73
74 // C 测试用例
slist_0100()75 void slist_0100()
76 {
77 char result[100];
78
79 // 插入节点到链表
80 insert_node(NODE_TEN);
81 insert_node(NODE_TWENTY);
82 insert_node(NODE_THIRTY);
83
84 // 验证链表内容是否符合预期
85 traverse_list(result, sizeof(result));
86 EXPECT_STREQ("slist_0100", result, "30 20 10 ");
87
88 // 删除节点并验证链表内容
89 delete_node(NODE_TWENTY);
90 traverse_list(result, sizeof(result));
91 EXPECT_STREQ("slist_0100", result, "30 10 ");
92 }
93
main()94 int main()
95 {
96 slist_0100();
97 return t_status;
98 }
99