复习四:链表——数据结构的的前奏之链表元素的遍历、删除以及链表中元素的删除

Writted by Bruth_Lee in Southwest universiy of Science and Technology.
//链表的遍历、链表元素的删除以及链表的删除
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct node {
int value;
struct node *next;
}Node;
typedef struct list {
Node *head;
Node *tail;
}List;
int main()
{
void add(List *list, int number);
int number;
List list;//Set up a chain called list--建立一个叫list的链表
list.head = list.tail = NULL;
while (cin >> number && number != -1)
{
add(&list, number);
}
Node *q;
for (q = list.head; q; q=q->next)//Travering th chain list--遍历链表
{
cout << q->value << " ";
}
cout << endl;
cin >> number;//Enter the element that you want to delete--输入要删除的元素
Node *p = NULL;
for (q=NULL, p = list.head; p;q=p, p = p->next)//Delete the element in the list--删除链表中的元素
{
if (p->value == number) {//The element has been found in the list--在链表中找到了该元素
if (q) {//If the element is not a head node--如果该元素不是头结点
q->next = p->next;//Point the pointer field of the former one of the element to the pointer field of element--将该元素前一个的指针域指向该元素的指针域
}
else {
list.head = p->next;//Point the head pointer to the pointer field of element--将头指针指向该元素的指针域
}
free(p);//Release the node--释放该节点
break;
}
}
for (q = list.head; q; q = q->next)//Travering th chain list that has been delete a element--遍历删除一个元素后的链表
{
cout << q->value << " ";
}
cout << endl;
//链表的删除--Delete the chian_list
for (p = list.head; p; p = q)
{
q = p->next;
free(p);
}


return 0;
}
void add(List *list, int number)
{
Node *p = (Node *)malloc(sizeof(Node));
p->value = number;
p->next= NULL;
if (list->head)
{
list->tail->next = p;//Connect the newly opened space to the pointer field of tail--将新开辟的空间接到tail的指针域
}
else 
{
list->head = p;//Connect the newly openned space to the list->head--将新开辟的空间接到链表的头指针
}
list->tail = p;//Move the pointer of tail to the end--将尾指针移到末尾


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江湖无为

感谢你们的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值