#include<iostream>
using namespace std;
#include<assert.h>
#include<stack>
struct ListNode
{
int _data;
struct ListNode* _next;
ListNode(int x) :_data(x), _next(NULL)
{}
};
typedef ListNode Node;
void PushBack(Node* node,int data)
{
Node* newnode;
newnode = new Node(data);
newnode->_data = node->_data;
newnode->_next = node;
node = newnode;
}
void printList(Node* node)
{
while (node != NULL)
{
printf("%d ", node->_data);
node = node->_next;
}
printf("\n");
}
//合并两个有序链表
Node* Solution(Node* l1,Node* l2,Node* l3)
{
if (l1== NULL)
{
return l2;
}
if (l2 == NULL)
{
return l1;
}
while (l1&&l2)
{
if (l1->_data >= l2->_data)
{
PushBack(l3, l2->_data);
l2 = l2->_next;
}
else
{
PushBack(l3, l1->_data);
l1 = l1->_next;
}
}
return l3;
}
//删除无头链表非尾节点
void DeleteNoHeadNode(Node* pos)
{
assert(pos);
if (pos == NULL)
{
cout << "list is NULL";
}
else if (pos->_next == NULL)
{
cout << "pos is tial node";
}
else
{
Node* PosNext = pos->_next;
pos->_data = PosNext->_data;
pos->_next = PosNext->_next;
delete PosNext;
PosNext = NULL;
}
}
//从尾到头打印单链表
void PrintLast(Node* head)
{
stack<Node*> s;
Node* cur = head;
while (cur)
{
s.push(cur);
cur = cur->_next;
}
while (!s.empty())
{
cout << s.top()->_data<<" ";
s.pop();
}
}
void PrintLast_R(Node* head)
{
if (head != NULL)
{
if (head->_next != NULL)
{
PrintLast_R(head->_next);
cout << head->_data<<" ";
}
}
}
//逆置
Node* Reverse(Node* head)
{
Node* prev=NULL;
Node* cur=NULL;
Node* tmp=NULL;
if (head == NULL || head->_next == NULL)
{
return head;
}
cur = head;
while (cur)
{
tmp = cur;
cur = cur->_next;
tmp->_next = prev;
prev = tmp;
}
return prev;
}
struct ListNode
{
int _value;
ListNode*_next;
ListNode(int value = 0, ListNode*pnext = NULL)
:_value(value)
, _next(pnext)
{}
};
//寻找第K个节点
ListNode* FindK(ListNode*phead, const int k)//只能遍历一次
{
ListNode*first = phead;
ListNode*second = phead;
int temp = k;
while (temp--)
{
first = first->_next;
}
while (first)
{
first = first->_next;
second = second->_next;
}
return second;
}
//判断链表是否带环//O(n)
pair<Node<int>*, bool> IsExitsLoop(Node<int>* head)
{
assert(head);
Node<int>* fast = head;
Node<int>* slow = head;
while (fast&&fast->_next)
{
fast = fast->_next->_next;
slow = slow->_next;
if (fast == slow)
return make_pair(fast, true);
}
return make_pair(fast, false);
}
若带环求环的长度//O(n)
int length(Node<int>* head)
{
assert(head);
if (!IsExitsLoop(head).second)
return 0;
Node<int>* node = IsExitsLoop(head).first;
Node<int>* cur = node->_next;
int count = 1;
while (cur != node)
{
count++;
cur = cur->_next;
}
return count;
}
若带环求环的入口点//O(n)
Node<int>* FindLoopPort(Node<int>* head)
{
assert(head);
Node<int>* node = IsExitsLoop(head).first;
Node<int>* cur = head;
while (cur != node)
{
cur = cur->_next;
node = node->_next;
}
return cur;
}