简体   繁体   English

如何使用给定的递归在单链表中插入节点:1. 指向头节点的指针 2. 插入新节点的索引

[英]How can I insert a node in a singly linked list using recursion given: 1. a pointer to the head node 2. the index to insert the new node

The function below is the one I am trying to work on.下面的 function 是我正在尝试处理的那个。 The problem I am running into is that I do not know how to "keep" the pointer to the original head to the list as that is what I have to return after insertion.我遇到的问题是我不知道如何将指向原始头的指针“保持”到列表中,因为这是我在插入后必须返回的。

There is no Driver code so everything must be done inside this function.没有驱动程序代码,所以一切都必须在这个 function 中完成。

Because I must do this recursively I cannot just create a temporary node to point to the original head.因为我必须递归地执行此操作,所以我不能只创建一个临时节点来指向原始头。 I am just getting used to recursion and I cannot find a solution.我只是习惯了递归,我找不到解决方案。

NOTE: There are some other problems with my function as I believe it wouldn't work well for inserting a new node into the beginning and end of the linked list but I am confident I could work out those edge cases.注意:我的 function 还有一些其他问题,因为我认为将新节点插入链表的开头和结尾效果不佳,但我相信我可以解决这些边缘情况。

The main thing I am trying to learn is how to "store" the original head of my list.我想学习的主要内容是如何“存储”列表的原始头部。

All help is appreciated.感谢所有帮助。

 Node* insert(Node* head, int index, int data)
{

if (head == NULL) return NULL; // if list is empty

if (index == 1) // if we have accessed node before insertion
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->next = head->next; // new_node->next now links to the node next in the list
    head->next = new_node; // head->next links to new node
    new_node->data = data; // assigns new node its data
    return head; // not sure how to return original head
}
return insert(head->next, index - 1, data);

} }

For starters the parameter that specifies the position where a node has to be inserted should have an unsigned integer type, for example, size_t .对于初学者,指定必须插入节点的 position 的参数应该具有无符号 integer 类型,例如size_t Positions should start from 0 .位置应该从0开始。

The function can be defined the following way function可以这样定义

struct Node * insert( struct Node *head, size_t pos, int data )
{
    if (head == NULL || pos == 0 )
    {
        struct Node *new_node = malloc( sizeof( struct Node ) );
        new_node->next = head;
        new_node->data = data;
        head = new_node;
    }
    else
    {
        head->next = insert( head->next, pos - 1, data );
    }

    return head;
}

Here is a demonstrative program这是一个演示程序

#include <stdio.h>
#include <stdlib.h>

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

struct Node * insert( struct Node *head, size_t pos, int data )
{
    if (head == NULL || pos == 0)
    {
        struct Node *new_node = malloc( sizeof( struct Node ) );
        new_node->next = head;
        new_node->data = data;
        head = new_node;
    }
    else
    {
        head->next = insert( head->next, pos - 1, data );
    }

    return head;
}

void print( const struct Node *head )
{
    for (; head != NULL; head = head->next)
    {
        printf( "%d -> ", head->data );
    }
    puts( "null" );
}

int main( void )
{
    struct Node *head = NULL;

    head = insert( head, 0, 3 );
    print( head );

    head = insert( head, 0, 0 );
    print( head );

    head = insert( head, 1, 1 );
    print( head );

    head = insert( head, 2, 2 );
    print( head );
}

The program output is程序 output 是

3 -> null
0 -> 3 -> null
0 -> 1 -> 3 -> null
0 -> 1 -> 2 -> 3 -> null
Node *insertRecursive(Node* head,int pos,int val)
{
    if(pos==0 || head==NULL)
    {
        Node *newNode= new Node(val);
        newNode->next=head;
        head=newNode;
        return head;
    }
    else
        head->next = insertRecursive(head->next,pos-1,val);
    
}

Node* insert_Node_recursively(Node* head,int data,int position){ Node* insert_Node_recursively(Node* head,int data,int position){

//Inserting on the first node.
if(position==0){
    Node* newNode=new Node(data);
    newNode->next=head;
    head=newNode;
    return head;
}



if((head->next==NULL && position==0) /*for adding on the end of the list */   || position==1  /*Inserting on node in between */){
        Node* newNode=new Node(data);
        newNode->next=head->next;
        head->next=newNode;
        return head;
}
//in case the position exceeds the total number of nodes
if(head->next==NULL && position>0){
    return head;
}
else{
    head->next=insert_Node_recursively(head->next,data,position-1);
}

return head;   

} }

this will work I think, covered all the aspects我认为这会起作用,涵盖了所有方面

//if you have created a node using class then here is the solution
//to insert a node at a position recurssively

Node * insertRecursive(Node * head, int data , int key)
{
    if (head == NULL || key == 0)
    { 
        Node * newNode = new Node(data);
        newNode -> next = head;
        head = newNode;
    }
    else
    {
        head -> next = insertRecursive(head -> next , data , key - 1);
    } 
    return head;
}
//here is the full solution to add a node recursively at a position

#include<iostream>
using namespace std;

//the below code is for creation of class for node
class Node
{
    public:
        int data;
        Node * next;
    
    Node(int data) //constructor 
    {
        this -> data = data;
        next = NULL;
    }
};

//the below code is for creation of linked list 
//a terminator -1 is used to stop taking input
Node * takeInput()
{
    int data;
    cout<<"Enter the data of the node to be inserted ( use -1 to terminate 
    the insertion ) : ";
    cin>>data;
    Node * head = NULL;
    Node * tail = NULL;

    while(data != -1)
    {
        Node * newNode = new Node(data);
        if(head == NULL)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail->next=newNode;
            tail = tail -> next;
        }
        cout<<"Enter the data of the node to be inserted ( use -1 to 
        terminate the insertion ) : ";
        cin>>data;
    }
    return head;
}

//the below code is to print the linked list
void print(Node * head)
{
    if(head == NULL)
    {
        cout<<"The linked list id empty !"<<endl;
        return;
    }
    Node * temp = head;
    while(temp != NULL)
    {
        cout<<temp->data<<" ";
        temp = temp -> next;
    }
    cout<<endl;
}

//the below part is the main solution to the problem 
//insertion at a position using recursion
Node * insertRecursive(Node * head, int data , int key)
{
    if (head == NULL || key == 0)
    { 
        Node * newNode = new Node(data);
        newNode -> next = head;
        head = newNode;
    }
    else
    {
         head -> next = insertRecursive(head -> next , data , key - 1);
    }
    return head;
}

//this is the main from where all the function calls happen
int main()
{
    int data, key;
    Node * head = takeInput();
    print(head);
    cout<<"Enter the data of the node to be inserted : ";
    cin>>data;
    cout<<"Enter the position of insertion : ";
    cin>>key;
    head = insertRecursive(head,data,key);
    print(head);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在第 n 个位置后的单向链表中插入新节点? - How to insert new node in a singly linked list after nth position? 如何在不使用临时节点的情况下在单链表中插入新节点? - How to insert a new node in a singly linked list without using a temporary node? 我可以使用 C 在单链表中的当前节点之前插入一个节点吗? - Can I insert a node before current node in singly linked list using C? 如何在新的单向链表中返回单向链表的奇数索引节点?假设第一个节点的索引为 1 - How can I return the odd indexed nodes of a singly linked list in a new singly linked list ?Assume index of the first node as 1 单链表,如何返回指向新节点的指针 - Singly linked list, how to return a pointer to a new node 如何在单链表的开始,结束和选定位置插入节点? - How to insert node at begin ,end and selected position in singly linked list? 给定一个节点如何在单链表中找到前一个节点 - given a node how can I find previous node in a singly linked list 链表-如何在不移动头节点的情况下进行尾部插入 - Linked List - how to tail insert without moving head node C编程-将值插入到特定节点后的单链表中 - C Programming - Insert value into singly linked list after specific node 在单个链表中的任何索引处插入新节点 - insert new node at any index within a single linked list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM