链表总结1

// 1.给定一个链表的头指针,在一次遍历中,找出这个链表中的中间节点并返回。
// 基本思想: 设立两个指针,比如*p和*q。p每次移动两个位置,而q每次移动一个位置,当p到达最后一个节点时,q就是中间节点了。
// 2.查找链表中倒数第k个节点
// 基本思想: 两个指针,保持距离k
// 3.怎么判断链表中是否有环?
// 基本思想: 与5相似,若p能追上q,则有环,否则无环。
///*
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int n;
    struct node *next;
};

int return_middle(struct node* head)//返回链表的中间节点
{
    struct node*p=head;
    struct node*q=head;
    while(p->next!=NULL&&p->next->next!=NULL)
    {
        p=p->next->next;
        q=q->next;

    }
    return q->n;

}
int return_k(struct node* head,int k)//查找链表中倒数第k个节点
{
    struct node*p=head;
    struct node*q=head;
    int count=0;

    while(count<k)
    {
        if(!p)
        {
            cout<<"越界访问!!";
            return NULL;
        }
        p=p->next;
        count++;
    }
    while(p)
    {
        p=p->next;
        q=q->next;
    }
    return q->n;

}
bool remark(struct node* head)//判断链表中是否有环?
{
    struct node*p=head->next;
    struct node*q=head;
    while(p->next!=NULL&&p->next->next!=NULL)
    {
        if(p==q)
            return true;
        p=p->next->next;
        q=q->next;

    }
    return false;

}
struct node *creatnode(int n)//创建链表
{
    struct node *head=(struct node*)malloc(sizeof(struct node));
    struct node *p=NULL;
    struct node *q=NULL;

    head->n=1;
    head->next=NULL;
    p=head;

    for(int i=1;i<n;i++)
    {
        q=(struct node*)malloc(sizeof(struct node));
        q->n=i+1;
        q->next=NULL;

        p->next=q;
        p=q;
    }
    if(n<1)
    {
        free(head);
        return NULL;
    }
    else
        return head;
}

void prin(struct node* head)//打印链表
{
    struct node* p=head;
    if(p->next==NULL)
        cout<<"这是一个空链表"<<endl;
    while(p!=NULL)
    {
        cout<<p->n<<" ";
        p=p->next;
    }
    cout<<endl;
}
void main()
{
    struct node* head;
    head=creatnode(9);
    prin(head);
    cout<<"中间节点为:"<<return_middle(head)<<endl;
    cout<<"倒数第9个结点为:"<<return_k(head,9)<<endl;
    cout<<"越界访问时结果: "<<return_k(head,10)<<endl;//越界访问
    if(remark(head))
        cout<<"有环!!"<<endl;
    else
        cout<<"无环!!"<<endl;

}
//*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值