栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

单链表(面试算法题1)---学习链表的关键在于code

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单链表(面试算法题1)---学习链表的关键在于code

先把单链表构建起来

链表的结点结构体:

struct node{
    int     value;
    node    *next;
};
typedef node*Node;

单链表的初始化

Node init(){
    
    Node head = NULL;
    Node p = NULL;
    int tmp;
    cin>>tmp;

    head = new node;
    head->value = tmp;
    head->next = NULL;
    p = head;

    while(cin>>tmp){
        Node s = new node;
        s->value = tmp;
        s->next = NULL;
        p->next = s;
        p=s;
    }

    return head;
}

单链表的打印

void printList(Node head){
    if(head == NULL){
        return;
    }
    Node p = head;
    while(p != NULL){
        cout<value<<" ";
        p = p->next; 
    }
}

单链表释放结点(C++没有垃圾回收机制-->不然会导致内存泄漏)

void delList(Node head){
    Node p = head->next;
    while(p!=NULL){
        delete head;
        head = p;
        p = p->next;
    }
    delete head;
    head = NULL;
}

好了,let's

==>面题1

反转单链表


Node reverselinkedList(Node head){
    Node pre = NULL;
    Node next = NULL;

    while(head != NULL){
        next = head->next;
        head->next = pre;
        pre = head;
        head = next;
    } 
    
    return pre;
    
}

==>面题2

删除单链表中的某个值

Node removevalue(Node head,int elem){
    Node s = NULL;
    
    //先处理头部是elem的元素
    while(head != NULL){
        if(head->value != elem){
            break;
        }
        s = head;
        head = head->next;
        delete s;
        s = NULL;
    }

    //处理有elem的结点
    Node p = head;
    Node cur = head;
    while(cur != NULL){
        if(cur->value == elem){
            s = cur;
            p->next = cur->next;
            cur = cur->next;
            delete s;
            s = NULL;
        }else{
            p = cur;
            cur = cur->next;
        }
    }

      return head;

}

主函数

int main()
{

    Node head = NULL;
    head = init();
    printList(head);
    cout< 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/664296.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号