#include <iostream> using namespace std; struct Node { int data; Node* next; }; //检测给定链表是否有环 bool CheckList(const Node* MyNode ) { if (MyNode == NULL) { return false; } const Node *low = MyNode; Node *fast = MyNode->next; while ((fast!=NULL) && (fast->next!=NULL)) { low = low->next; fast = fast->next->next; if (low==fast) { return true; //有环 } } return false; } //查找环入口点 Node* FindLoopPoint(Node* InNode) { bool bIsLoop = false; if (InNode == NULL) { cout << "loop is null" << endl; return NULL; } Node* fptr = InNode; Node* sptr = InNode; while (sptr!=NULL && sptr->next!=NULL) { fptr = fptr->next; sptr = sptr->next->next; if (fptr == sptr) { bIsLoop = true; //存在环 break; } } if (bIsLoop == false) { cout << "no loop" << endl; return NULL; } else { fptr = InNode; while (fptr!=sptr) { fptr = fptr->next; sptr = sptr->next; } Node *rptr = fptr; return rptr; } } //链表逆序--递归 Node* ReverseList(Node *head) { if (NULL == head) //没有节点 { return head; } else if (NULL == head->next) //只有一个节点 { return head; } else { Node* rHead = ReverseList(head->next); head->next->next = head; head->next = NULL; return rHead; } } //链表逆序--非递归 Node* ReverseList2(Node*head) { if (head == NULL || head->next==NULL) { return head; } Node *p1 = head; Node *p2 = head->next; Node *p3 = head->next->next; p1->next = NULL; while(p3 != NULL) { p2->next = p1; p1 = p2; p2 = p3; p3 = p3->next; } p2->next = p1; head = p2; return head; } //已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序。(保留所有结点,即便大小相同 Node* Merge(Node* head1,Node* head2) { if (NULL == head1) { return head2; } if (NULL == head2) { return head1; } Node* head; Node *p1,*p2; if (head1->data < head2->data) { head = head1; p1 = head1->next; p2 = head2; } else { head = head2; p1 = head1; p2 = head2->next; } Node *p3 = head; while (p1!=NULL && p2!=NULL) { if (p1->data < p2->data) { p3->next = p1; p3 = p1; p1 = p1->next; } else { p3->next = p2; p3 = p2; p2 = p2->next; } } if (p1 != NULL) { p3->next = p1; } if (p2 != NULL) { p3->next = p1; } return head; } //递归 Node* Merge2(Node* head1,Node* head2) { if (NULL == head1) { return head2; } if (NULL == head2) { return head1; } Node* head; if (head1->data < head2->data) { head = head1; head->next = Merge2(head1->next,head2); } else { head = head2; head->next = Merge2(head1,head2->next); } return head; }