2个回答
展开全部
#include <iostream>
using namespace std;
struct Node
{
int elem;
Node* next;
};
struct List
{
Node* head = NULL;
};
//查找前驱节点
Node* find_pre(List list, int elem)
{
if (!list.head) return NULL;
Node* node = list.head;
while (node->next && node->next->elem < elem) node = node->next;
return node;
}
//插入节点
void ins_elem(List &list, int elem)
{
Node* pre = find_pre(list, elem);
if (!pre)
{
list.head = (Node*)malloc(sizeof(Node)); //头结点暂不存放值
list.head->next = (Node*)malloc(sizeof(Node));
list.head->next->elem = elem;
list.head->next->next = NULL;
return;
}
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->elem = elem;
new_node->next = pre->next;
pre->next = new_node;
}
//删除节点
void del_elem(List &list, int elem)
{
Node* pre = find_pre(list, elem);
if (!pre) return;
while (pre->next->elem == elem)
{
Node* next = pre->next;
pre->next = next->next;
free(next);
}
}
//遍历链表
void traverse(List list)
{
if (!list.head) return;
Node* node = list.head->next;
while (node)
{
cout << node->elem << " ";
node = node->next;
}
cout << endl;
}
//销毁链表
void destory(List &list)
{
if (!list.head) return;
Node* node = list.head->next;
while (node)
{
Node* next = node->next;
free(node);
node = next;
}
}
int main()
{
int arr[5] = { 1, 2, 2, 4, 5 };
List list;//声明链表
for (int i = 0; i < 5; i++)
{
ins_elem(list, arr[i]);
}
traverse(list);
del_elem(list, 2);
traverse(list);
destory(list);
return 0;
}
using namespace std;
struct Node
{
int elem;
Node* next;
};
struct List
{
Node* head = NULL;
};
//查找前驱节点
Node* find_pre(List list, int elem)
{
if (!list.head) return NULL;
Node* node = list.head;
while (node->next && node->next->elem < elem) node = node->next;
return node;
}
//插入节点
void ins_elem(List &list, int elem)
{
Node* pre = find_pre(list, elem);
if (!pre)
{
list.head = (Node*)malloc(sizeof(Node)); //头结点暂不存放值
list.head->next = (Node*)malloc(sizeof(Node));
list.head->next->elem = elem;
list.head->next->next = NULL;
return;
}
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->elem = elem;
new_node->next = pre->next;
pre->next = new_node;
}
//删除节点
void del_elem(List &list, int elem)
{
Node* pre = find_pre(list, elem);
if (!pre) return;
while (pre->next->elem == elem)
{
Node* next = pre->next;
pre->next = next->next;
free(next);
}
}
//遍历链表
void traverse(List list)
{
if (!list.head) return;
Node* node = list.head->next;
while (node)
{
cout << node->elem << " ";
node = node->next;
}
cout << endl;
}
//销毁链表
void destory(List &list)
{
if (!list.head) return;
Node* node = list.head->next;
while (node)
{
Node* next = node->next;
free(node);
node = next;
}
}
int main()
{
int arr[5] = { 1, 2, 2, 4, 5 };
List list;//声明链表
for (int i = 0; i < 5; i++)
{
ins_elem(list, arr[i]);
}
traverse(list);
del_elem(list, 2);
traverse(list);
destory(list);
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询