1. 前言
好久没写过单链表了,再刷题的时候遇见了,然后就写了下面的答案,但是在评论区看见有的同学说删除的时候要用到二级指针,但是我觉得一级指针就可以做到。下面看代码。
2. 正文
以下是我的代码
读入10个复数,建立对应链表,然后求所有复数的和。
#includeusing namespace std;
typedef struct ListPlural{
int real;
int imaginary;
ListPlural *next;
}listdata;
//创建头节点
listdata *creatListHead(){
listdata * head = new listdata;
if(head == NULL){
return NULL;
}
head -> next = NULL;
return head;
}
//增加数据
void addData(listdata *head, const int &real, const int &imaginary){
listdata *data = new listdata;
listdata * temp;
data -> real = real;
data -> imaginary = imaginary;
for(temp = head; temp -> next != NULL; temp = temp -> next){}
temp -> next = data;
data -> next = NULL;
}
//链表的遍历
void listTraverse(listdata *head){
listdata *temp;
int real = 0, imaginary = 0;
for(temp = head -> next; temp != NULL; temp = temp -> next){
real += temp -> real;
imaginary += temp -> imaginary;
}
cout << real << "+" << imaginary << "i" << endl;
}
//链表的删除
void listDelete(listdata *head){
listdata *temp = head -> next;
while(head-> next -> next != NULL){
temp = head->next;
head -> next = head -> next->next;
delete temp;
}
temp = head -> next;
delete temp;
delete head;
}
using namespace std;
//任务函数
int main()
{
listdata *head;
int real, imaginary;
head = creatListHead();
for(int i = 1; i > real,cin >> imaginary;
addData(head, real, imaginary);
}
listTraverse(head);
listDelete(head);
return 0;
}
下面是另一位同学的代码部分
void link_free(STU **p_head)
{
STU *p_mov;
while(*p_head!=NULL)
{
p_mov=*p_head;
*p_head=p_mov->next;
free(p_mov);
}
}
3. 备注
以上就是两种释放方式,请各位看到有问题或是自己的见解,在评论区讨论。
>>>>>>
生命始于精彩,却不止于精彩。
>>>>>>
好像越来越烦躁了。