1、单链表逆序,在原链表数据的基础上进行调整
Node * Reverse(Node *head)
{
if(head==NULL) return NULL;
if(head->next==NULL) return head;
Node *t=head->next;
Node *p=head;
p->next=NULL;
while(t!=NULL)
{
p=t;
t=t->next;
p->next=head;
head=p;
}
return p;
int main(int argc, const char* argv[])
{
Node* head = create_node(0);
for (int i = 0;i < 10;i++)
{
//add_tail_list(head,i);
add_head_list(head, i);
}
Node *p=Reverse(head);
show_list(p);
return 0;
}
2、找出单链表的倒数第n个结点
//单链表倒数结点
Node *daoshu2(Node *head,TYPE n)
{
Node *slow=head;
Node *fast=head;
for(int i=0;i<n;i++)
{
fast=fast->next;
}
while(fast!=NULL)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
int main(int argc, const char* argv[])
{
Node* head = create_node(0);
for (int i = 0;i < 5;i++)
{
add_tail_list(head,rand()%20);
// add_head_list(head, i);
}
Node *a= daoshu2(head,5);
printf("%d \n",a->data); // 倒数第几个
show_list(head);
Node* find_nth_from_end(Node* head, int n) {
Node *slow = head;
Node *fast = head;
// 让快指针先移动n步
for (int i = 0; i < n; i++) {
if (fast == NULL) {
return NULL; // 链表长度小于n
}
fast = fast->next;
}
// 一起移动直到快指针到达末尾
while (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
3、判断链表中是否有环
int link_rear(Node *head)
{
Node *slow=head;
Node *fast=head;
while (fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return 1;
}
return 0;
}
int main(int argc, const char* argv[])
{
Node* head = create_node(0);
for (int i = 0;i < 10;i++)
{
add_head_list(head, i);
}
int a=link_rear(head);
printf("%d\n ",a);
show_list(head);
return 0;
4、找出环形链表的入口
// 功能:找出环形链表的入口节点
Node * link_rear_inlet(Node *head)
{
Node *slow=head;
Node *fast=head;
while (fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
Node *p1=head;
Node*p2=slow;
while(p1!=p2)
{
p1=p1->next;
p2=p2->next;
}
return p1;
}
}
return NULL;
}
5、合并两个有序链表,合并后依然有序
//合并两个顺序链表
Node *merge_link(Node *head,Node *head2)
{
Node *L3=create_node(0);
Node *p1=head->next;
Node *p2=head2->next;
Node *p3=L3;
while(p1&&p2)
{
if(p1->data<=p2->data)
{
p3->next=p1;
p1=p1->next;
}else
{
p3->next=p2;
p2=p2->next;
}
p3=p3->next;
}
p3->next=p1==NULL?p2:p1;
return L3;
}
6、判断两个链表是否是Y型链表,找出相交点
//计算链表的长度
int length_link(Node*head)
{
Node *p=head;
int length=0;
while(p!=NULL)
{
length++;
p=p->next;
}
return length;
}
//寻找交叉链表的结点
Node * cross_node(Node *head,Node *head2)
{
int lengthA=length_link(head);
int lengthB=length_link(head2);
int a=lengthA-lengthB;
if(a>0)
{
for(int i=0;i<a;i++)
{
head=head->next;
}
}else
{
for(int i=0;i<-a;i++)
{
head2=head2->next;
}
}
while(head!=NULL&&head2!=NULL)
{
head=head->next;
head2=head2->next;
if(head==head2) return head;
}
return NULL;
}
多数人都拥有自己不了解的能力和机会,都有可能做到未曾梦想的事情。
——戴尔·卡耐基