欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C/C++ 链表翻转(单链表)

程序员文章站 2022-06-22 23:46:22
...

本人设计的链表翻转(单链表),含增删查改全部代码,接口基本复制过去就能用了

如果发现错误欢迎指正!

翻转具体代码在本文最后一个函数中 

#include <iostream>
using namespace std;

struct node
{
    int data;
    struct node* next;
};

void inser_node(struct node *head,int data)
{
    struct node *new_node = new struct node;

    new_node->data = data;
    new_node->next = NULL;

    //找到最后一个节点
    struct node *pos = head;
    while(pos->next != NULL)
    {
        pos = pos->next;
    }
    //插入节点
    pos->next = new_node;

}

void updata_node(struct node *head,int old_data,int new_data)
{
    //1.找到需要修改的数据 
    struct node *pos =  head->next; 

    while (pos!= NULL)
    {
        if(pos->data == old_data)
        {
            pos->data = new_data;
        }
      pos = pos->next;
    }
}

//遍历
void show_list(struct node*head)
{
    //指向第一个节点
    struct node *pos = head->next;

    while(pos != NULL)
    {
        cout << pos << endl;
        pos = pos->next;
    }
}

void del_node(struct node *head,int del_data)
{
    //定义一个指着指向pos的前一个
    struct node *prv = head;
    struct node *pos = head->next;

    //利用pos找到需要删除的数据
    while(pos != NULL)
    {
        if(pos->data == del_data)//找到要删除的数据
        {
            //进行删除
            prv->next = pos->next;
            pos->next =NULL;

            delete pos;

            pos = prv;//回去原来的位置
            
        }
        prv = pos;//保存pos的上一个位置
        pos = pos->next;
    }
}

//头取头插法
void Rollover_list(struct node *head)
{
    //定义一个新的临时头节点 
    struct node *tmp_head = new  struct node; 
    tmp_head->next = NULL; 
    tmp_head->data = 0;
 
    //1.进行头取  
    while (head->next != NULL )  //还有节点 
    {
        struct node *pos = head->next; //指向头的下一个节点  

        head->next = pos->next; //取出  
        pos->next = NULL;

        //头插 
        pos->next = tmp_head->next;
        tmp_head->next = pos; 
    }
    
    head->next = tmp_head->next;

    delete tmp_head;
}