单链表算法 删除 L 中第 1、3、5…结点。

设带头结点的非空单链表 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;
}

欢迎各位大佬的指正

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值