struct ListNode {
int data;
struct ListNode *next;
};
void printList( struct ListNode *L )
{
struct ListNode *p = L;
while (p) {
cout<<"data="<<p->data<<endl;
p = p->next;
}
}
struct ListNode* initList()
{
struct ListNode *node=NULL;
node=(struct ListNode*)malloc(sizeof(struct ListNode));
memset(node,0,sizeof(struct ListNode));
node->data=0;
node->next=NULL;
return node;
}
int listPushback(struct ListNode*L,int addNum)
{
struct ListNode *temp=L;
struct ListNode *pre=L;
while(temp!=NULL)
{
pre=temp;
temp=temp->next;
}
struct ListNode *newNode=(struct ListNode*)malloc(sizeof(struct ListNode));
memset(newNode,0,sizeof(struct ListNode));
newNode->data=addNum;
newNode->next=NULL;
pre->next=newNode;
return 0;
}
int listPopBack(struct ListNode*L)
{
if(L==NULL)
return -1;
struct ListNode *temp=L->next;
struct ListNode *pre=L;
while(temp!=NULL)
{
if(temp->next==NULL)
{
pre->next=temp->next;
int x=temp->data;
free(temp);
temp=NULL;
break;
}
pre=temp;
temp=temp->next;
}
return 0;
}
//首节点还没做处理(已处理)
int listDel(struct ListNode*L,int index)
{
if(L==NULL || (index<0))
return -1;
struct ListNode *temp=L;
struct ListNode *head=L;
int i=0;
if(index==0)
{
temp=temp->next;
while(temp!=NULL)
{
head->data=temp->data;
temp=temp->next;
head=head->next;
}
listPopBack(L);
return 0;
}
while(temp!=NULL)
{
if(i==index)
{
head->next=temp->next;
free(temp);
temp=NULL;
return 0;
}
head=temp;
temp=temp->next;
i++;
}
return 0;
}
void freeList(struct ListNode *L)
{
while(L!=NULL)
{
struct ListNode *temp=L;
L=L->next;
free(temp);
cout<<"释放节点一次"<<endl;
}
}
int main()
{
struct ListNode* nodeList=initList();
listPushback(nodeList,1);
// listPushback(nodeList,2);
// listPushback(nodeList,3);
// listPushback(nodeList,4);
printList(nodeList);
listDel(nodeList,0);
//删除尾结点后
cout<<"删除尾结点后"<<endl;
printList(nodeList);
freeList(nodeList);
return 0;
}