链表——不带头结点
程序员文章站
2024-03-21 12:57:40
...
创建不带头结点单链表
设计递归算法,删除单链表L中所有值为x的结点
#include<bits/stdc++.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode, *LinkList;
//不带头结点创建单链表
LinkList CreateList_HeadInsert(LinkList &L, int n)
{
L = (LinkList)malloc(sizeof(LNode));
L = NULL;
int number;
LNode *p;
for(int i = 0;i<n;i++)
{
cin>>number;
p = new LNode;
p -> data = number;
p -> next = L;
L = p;
}
return L;
}
void List_Print(LinkList &L)
{
cout<<"The list is : ";
LNode *p;
p = L;
while(p!= NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
//递归删除不带头结点 单链表L 值为x结点
void Delete_x(LinkList &L, int x)
{
if(L == NULL)
return ;
if(L->data == x)
{
LNode *p = L;
L= L->next;
free(p);
Delete_x(L,x);
}
if(L->data != x)
{
Delete_x(L->next,x);
}
}
int main()
{
LinkList L1;
int n;
cin>>n;
CreateList_HeadInsert(L1, n);
List_Print(L1);
Delete_x(L1, 2);
List_Print(L1);
}