链表的基本操作(引用)

//
// Created by 刘彪 on 2020/2/29.
//

#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
typedef struct node{
    int no;
    struct node *next;
}Node;

void create(Node *&h){
    Node *s,*r;
    int n;
    h = NULL;
    cout<<"数序(负数结束):";
    cin >> n;
    while(n>0){
        s = (Node *)malloc(sizeof(Node));
        s->no = n;
        s->next = NULL;
        if(h==NULL){
            h = s;
            r = h;
        }else{
            r->next = s;
            r = s;
        }
        cin>>n;
    }
}

int len(const Node *h){
    int i=0;
    while(h!=NULL){
        i++;
        h=h->next;
    }
    return i;
}
void del(Node *&h,int i){
    Node *p=h,*q;
    if(i<1 || i>len(h))  return;
    if(i==1){
        h = h->next;
        free(p);
    }else{
        while(i-->2) p=p->next;
        q = p->next;
        p->next = q->next;
        free(q);
    }
}
void disp(const Node *h){
    cout<<"链表";
    while(h!=NULL){
        cout<<h->no<<" ";
        h = h->next;
    }
    cout<<endl;
}

int main(){
    Node* head;
    int i;
    create(head);
    disp(head);
    cout<<"length:"<<len(head)<<endl;
    cout<<"删除第几个结点:";
    cin>>i;
    del(head,i);
    disp(head);
    return 0;
}



//p120

全部评论

相关推荐

08-16 10:51
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务