注释:这段时间在参加校招,问了很多链表的问题,虽然都可以完全不错的写出来,但却花了不少时间,一怒之下我就把链表的基本所有操作都重新编写一遍
备注:适合于才学链表和有一些链表操作的经验的同学看,代码全部都可以通过,可以放心使用
头文件:list.h
#include <iostream>
#include <assert.h>
using namespace std;
#include <vector>
struct Node
{
int value;
struct Node *next;
Node(int v=0):value(v),next(NULL)
{}
};
class List
{
public:
void insert(int value=0)
{
Node *node=BuyNode(value);
if(head==NULL)
{
head=node;
return;
}
//头插
node->next=head->next;
node->next=head;
head=node;
}
void show(Node *Head)
{
Node *cur=Head;
while(cur)
{
cout<<cur->value<<" ";
cur=cur->next;
}
cout<<endl;
}
void print()
{
print(head);
}
//链表逆制
void resver()
{
resver(head);
}
//从尾打印链表
void print_tail()
{
print_tail(head);
}
//在O(1)时间内删除一个链表
void remove(int value)
{
remove(head,value);
}
//链表的倒数第k个节点
Node* get_k(int k)
{
return get_k(head,k);
}
//寻找两个链表的公共节点
Node* find_comm_node(List *list1,List *list2)
{
if(list1 ==NULL || list2 ==NULL)
return NULL;
return find_comm_node(list1->head,list2->head);
}
//合并两个有序链表
Node* megre(List *head,List *phead)
{
if(head==NULL || phead==NULL)
return NULL;
return megre(head->head,phead->head);
}
//链表合并第二种写法
Node* Megre(List *head,List *phead)
{
if(head==NULL || phead==NUL