//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;
//}
逆置,查找倒数第K个节点,Add函数不用四则运算的实现
最新推荐文章于 2020-07-23 15:12:07 发布