逆置,查找倒数第K个节点,Add函数不用四则运算的实现

//1 逆置单链表,查找倒数第K个节点只遍历一遍
#include<iostream>
using namespace std;
#include<malloc.h>
typedef int DataType;

struct ListNode
{
	DataType _data;
	ListNode* _next;

	ListNode(const DataType& x)
		:_data(x)
		, _next(NULL)
	{}
};

ListNode* BuyNode(const DataType& x)
{
	ListNode* cur = (ListNode*)malloc(sizeof(DataType));
	cur->_data = x;
	cur->_next = NULL;
	return cur;
}

void Printf(ListNode* list)
{
	ListNode* cur = list;
	if (cur == NULL)
		return;
	while (cur)
	{
		cout << cur->_data << " ";
		cur = cur->_next;
	}
	cout << endl;
}

void PushFront(ListNode** list, const DataType& x)
{
	if (*list == NULL)
	{
		*list = BuyNode(x);
	}
	else
	{
		ListNode* next = *list;
		*list = BuyNode(x);
		(*list)->_next = next;
	}
}
void PushBack(ListNode** list,const DataType& x)
{
	ListNode* tail = *list;
	if (*list == NULL)
	{
		*list = BuyNode(x);
	}
	else
	{
		while (tail->_next)
		{
			tail = tail->_next;
		}
		tail->_next = BuyNode(x);
	}
}


ListNode* CountBackwards(ListNode* list, int k)//查找倒数第K个节点
{
	if (list == NULL)
	{
		return NULL;
	}

	ListNode* fast = list;
	ListNode* slow = list;
	while (--k)
	{
		fast = fast->_next;
	}
	while (fast->_next)
	{
		slow = slow->_next;
		fast = fast->_next;
	}
	return slow;
}

void ReverseList(ListNode** list)
{
	if (*list == NULL||(*list)->_next==NULL)
	{
		return;
	}
	ListNode* cur = *list;
	ListNode* tmp = NULL;
	*list = NULL;
	while (cur)
	{
		tmp = cur;
		cur = cur->_next;
		PushFront(list, tmp->_data);
	}
}

void Test1()   //查找倒数第K个节点
{
	ListNode* list = NULL;
	PushBack(&list, 2);
	PushBack(&list, 5);
	PushBack(&list, 9);
	PushBack(&list, 8);
	Printf(list);
	ListNode* cur=CountBackwards(list, 2);
	cout << cur->_data << endl;
}

void Test2()   //逆置单链表
{
	ListNode* list = NULL;
	PushFront(&list, 2);
	PushFront(&list, 5);
	PushFront(&list, 9);
	PushFront(&list, 8);
	Printf(list);
	ReverseList(&list);
	Printf(list);

}
int main()
{
	Test2();
	return 0;
}

2实现Add函数,不能用四则运算  -->
//#include<stdio.h>
//
//int Add(int num1,int  num2)
//{
//	int tmp = 0;
//	while (num2)
//	{
//		tmp = num1^num2;
//		num2 = (num1&num2) << 1;
//		num1 = tmp;
//	}
//	return num1;
//}
//
//int main()
//{
//	int sub = Add(4,5);
//	printf("%d \n", sub);
//	return 0;
//}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值