单链表操作
单链表操作
链表节点定义:
struct node {
int value;
struct node* next;
};
#### 反转单链表
struct node* reverse(struct node* list)
{
if (NULL == list) {
return NULL;
}
struct node* list_r = list;
list = list->next;
list_r->next = NULL;
struct node* p;
while (NULL != list) {
p = list;
list = list->next;
p->next = list_r;
list_r = p;
}
return list_r;
}
#### 合并单链表
struct node* merge(struct node* list1, struct node* list2)
{
if (NULL == list1 && NULL == list2) {
return NULL;
}
if (NULL == list1) {
return list2;
}
if (NULL == list2) {
return list1;
}
struct node* list;
struct node* p;
if (list1->value <= list2->value) {
list = list1;
list1 = list1->next;
} else {
list = list2;
list2 = list2->next;
}
p = list;
while (NULL != list1 && NULL != list2) {
if (list1->value <= list2->value) {
p->next = list1;
p = list1;
list1 = list1->next;
} else {
p->next = list2;
p = list2;
list2 = list2->next;
}
}
if (NULL != list1) {
p->next = list1;
}
if (NULL != list2) {
p->next = list2;
}
return list;
}
#### 判断单链表是否存在环
bool has_loop(struct node* list)
{
if (NULL == list) {
return false;
}
struct node* p1 = list;
struct node* p2 = list;
while (NULL != p2->next) {
p2 = p2->next;
if (NULL != p2->next) {
p2 = p2->next;
} else {
return false;
}
p1 = p1->next;
if (p2 == p1) {
return true;
}
}
return false;
}
#### 查找有环单链表的环开始点
struct node* find_loop_port(struct node* list)
{
if (NULL == list) {
return NULL;
}
struct node* p1 = list;
struct node* p2 = list;
bool hasloop = false;
while (NULL != p2->next) {
p2 = p2->next;
if (NULL != p2->next) {
p2 = p2->next;
} else {
break;
}
p1 = p1->next;
if (p2 == p1) {
hasloop = true;
break;
}
}
struct node* p3 = NULL;
if (true == hasloop) {
if (p2 == list) {
return list;
} else {
p3 = list;
while (true) {
p2 = p2->next;
p3 = p3->next;
if (p2 == p3) {
break;
}
}
}
}
return p3;
}
#### 移除单链表的特定节点
struct node* remove_if(struct node* list, bool(*cond_func)(struct node*))
{
if (NULL == list) {
return list;
}
struct node** ppNode = &list;
for (struct node* pNode = *ppNode; NULL != pNode; pNode = *ppNode) {
if (true == cond_func(pNode)) {
if (pNode == list) {
list = pNode->next;
}
*ppNode = pNode->next;
free(pNode);
} else {
ppNode = &(pNode->next);
}
}
return list;
}