设带头结点的非空单链表 L,设计一个算法删除 L 中奇数序号
的结点,即删除 L 中第 1、3、5…结点。
删除单链表中的奇数节点可以运用跳格的思想,跳过奇数节点——从头结点开始,将连接指针指向下一个节点的连接指针指向的节点
以下包括节点的创建和删除(自带各个步骤的测试)
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef int Elemtype;
typedef struct list
{
Elemtype data;
struct list* next;
} listnode;
//创建新节点
listnode* creat_node(Elemtype x)
{
listnode* newnode;
newnode=(listnode*)malloc(sizeof(listnode));
newnode->data=x;
newnode->next=NULL;
return newnode;
}
//创建链表
listnode* creat_line(listnode* &first,Elemtype a[],Elemtype n)
{
first=(listnode*)malloc(sizeof(listnode));;
first->next=NULL;
// cout<<"3dataover"<<endl;
listnode *tail=first;
//tail=(listnode*)malloc(sizeof(listnode));; //尾节点
cout<<"begin:...."<<endl;
for(int i=0;i<n;i++)
{
listnode *p=creat_node(a[i]);
tail->next=p;
tail=p;
cout<<tail->data<<endl;
}
cout<<"创建完了"<<endl;
//listnode *q;//移动节点
// cout<<"5dataover"<<endl;
return first;
}
//删除奇节点
listnode* delete_odd(listnode* &first,Elemtype n)
{
listnode *q=first;//移动节点
listnode *q_next=q->next;
while(q_next!=NULL)
{
q->next=q_next->next;
//从头节点开始将指针指向下一个的下一个节点
q=q->next;
free(q_next);
if(q==NULL)
break;
q_next=q->next;
}
}
int main()
{
Elemtype n;
cin>>n;
Elemtype *a=(Elemtype*)malloc(n*sizeof(Elemtype));
for(int i=0;i<n;i++)
{
cin>>a[i];
}
listnode *first;//头指针
first=creat_line(first,a,n);
cout<<first->next->next->data<<endl;//测试是否合理
delete_odd(first,n);//删除
cout<<"删除结束"<<endl;
listnode *q;//移动节点
q=first->next;
// cout<<q->data<<endl;//测试
//输出
listnode *q_next=q->next;
while(q)
{
cout<<q->data<<' ';
q=q_next;
q_next=q_next->next;
}
return 0;
}
欢迎各位大佬的指正