C实现单链表

typedef int DataType;
typedef struct ListNode
{
	DataType data;
	struct ListNode* next;
}ListNode;

//初始化链表
void InitList(ListNode** pphead)
{
	*pphead = NULL;
}

//创建节点
ListNode* BuyNode(DataType x)
{
	ListNode* tmp = (ListNode*)malloc(sizeof(ListNode));
	assert(tmp);
	tmp->data = x;
	tmp->next = NULL;
	return tmp;
}

//尾插
void PushBack(ListNode** phead,DataType x)
{
	if(NULL == *phead)
	{
		*phead = BuyNode(x);
	}
	else
	{
		ListNode* tial = *phead;
		while(tial->next != NULL)
		{
			tial = tial->next;
		}
		tial->next = BuyNode(x);
	}
}

//打印
void Print(ListNode* phead)
{
	ListNode* tmp = phead;
	while(tmp != NULL)
	{
		printf("%d->",tmp->data);
		tmp = tmp->next;
	}
	printf("NULL");
	printf("\n");
}

//前插
void PushFront(ListNode** phead,DataType x)
{
	if(*phead == NULL)
	{
		*phead = BuyNode(x);
	}
	else
	{
		ListNode* tmp = BuyNode(x);
		tmp ->next = *phead;
		*phead = tmp;
	}
}

//尾删
void PopBack(ListNode** phead)
{
	if(*phead == NULL)
	{
		printf("kd");
		return;
	}
	else
	{
		ListNode* tmp = *phead;
		(*phead) = (*phead)->next;
		free(tmp);
	}	 
}

//找节点
ListNode* Find(ListNode* phead,DataType x)
{
	if(NULL == phead)
	{
		printf("KONG");
		return;
	}
	else
	{
		ListNode* cur = phead;
		while(cur)
		{
			if(cur->data = x)
			{
				return cur;
			}
			cur = cur->next;
		}
		return cur;
	}
}

//插入
void Insert(ListNode* pos,DataType x)
{
	ListNode* tmp = BuyNode(x);
	tmp->next = pos->next;
	pos->next = tmp;
}

//翻转单链表
ListNode* Reverse(ListNode* phead)
{
	ListNode* newhead = NULL;
	ListNode* tmp = phead;
	while(tmp)
	{
		ListNode* cur = tmp;
		tmp = tmp->next;
		cur->next = newhead;
		newhead = cur;
		/*ListNode* cur = tmp->next;
		tmp->next = newhead;
		newhead = tmp;
		tmp = tmp->next;*/
	}
	return newhead;
}

//从尾到头打印单链表
void printListFromTailToHead(ListNode* head)
    {
        if(head == NULL)
            {
            	return;           
       	    }
      	ListNode *newhead = NULL;
        ListNode *cur = head;
        while(cur)
            {
         		ListNode *tmp = cur;
            	cur = cur->next;
            	tmp->next = newhead;
            	newhead = tmp;
            }
        ListNode *p = newhead;
        while(p)
            {
            	cout<<p->val<<endl;
                p = p->next;            
            }
    }

个站

首页_码到城攻码到城攻分享但不限于IT技术经验技巧、软硬资源、所闻所见所领会等,站点提供移动阅读、文章搜索、在线留言、支付打赏、个人中心、免签支付等功能https://www.codecomeon.com/index

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值