采用得是纯指针链表
注意点
- 内存的申请
使用malloc函数,该函数返回的是void*形式的地址需要使用强转换,也就是
(struct node*)malloc(sizeof(struct node));
- struct的指针形式,其本身也是一个地址,例如
struct node* pos = (struct node*)malloc(sizeof(struct node));
cout<<pos<<endl;
//输出: 0x1deb9711740
提取struct指针中的信息就用->就行了,若不是指针就用 . 来提取信息即可
- 最终要的一点就是内存的释放,当删除结点的时候如果不用free()函数来释放地址的话,就会有一些数据占用着内存,但是已经没有意义了,也有可能在下次申请内存的时候申请到这些有数据的内存造成一些错误
所以最后的代码就是
#include<bits/stdc++.h>
using namespace std;
struct node
{
int a;
struct node *next;
};
struct node* createNode(int num)
{
struct node* ret = (struct node*)malloc(sizeof(struct node));
ret->a = num;
ret->next = NULL;
return ret;
}
void insertbyHead(struct node* head, int num)
{
struct node* newnode = createNode(num);
newnode->next = head->next;
head->next = newnode;
}
void deleteNode(struct node* head, int posnum)
{
struct node* fronnode = head;
struct node* posnode = head->next;
while(posnode != NULL)
{
if(posnode->a == posnum)
{
fronnode->next = posnode->next;
struct node* freepos = posnode;
posnode = posnode->next;
free(freepos);
}
else fronnode = posnode, posnode = posnode->next;
}
}
int main()
{
struct node* head = createNode(0);
insertbyHead(head, 1);
insertbyHead(head, 3);
insertbyHead(head, 5);
struct node* tail = head;
while(tail)
{
if(tail->a) cout<<tail->a<<" ";
tail = tail->next;
}
cout<<endl;
deleteNode(head, 3);
tail = head;
while(tail)
{
if(tail->a) cout<<tail->a<<" ";
tail = tail->next;
}
return 0;
}
5 3 1
5 1