链表实现-使用单独的Insert(), Delete(), Print()函数

Linked List Implementation - using separate Insert(), Delete(), Print() functions

本文关键字:Delete 函数 Print Insert 实现 单独 链表      更新时间:2023-10-16

我试图通过利用三个独立的函数在c++上实现链表:

  1. Insert(int x, int n) -获取要插入的数字(x)和要插入的位置(n),从位置1开始。
  2. Delete(int n) -删除从位置1开始的位置(n)上的数字;
  3. Print() -打印链表中的元素。

下面是我的c++代码:

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
struct Node {
    int data;
    Node* next;
};
Node* head;
void Print()
{
    cout << "The List is:" ;
    Node* temp = head;
    while (temp -> next != NULL)
    {
        temp = temp -> next;
        cout << " " << temp -> data;
    }
}
void Delete(int n)
{
    if ( n == 1 )
    {
        Node* temp = head;
        head = temp -> next;
        delete temp;
        return;
    }
    Node* temp1 = head;
    for(int i = 0; i < n-2; i++)
    {
        temp1 = temp1 -> next;
    }
    Node* temp2 = temp1 -> next;
    temp1 -> next = temp2 -> next;
    delete temp2;
}
void Insert(int x, int n)
{
    Node* temp = new Node();
    temp -> data = x;
    temp -> next = NULL;
    if ( n == 1 )
    {
        temp -> next = head;
        head = temp;
        return;
    }
    Node* temp1 = head;
    for (int i = 0; i < n-2; i++)
    {
        temp1 = temp1 -> next;
    }

    temp -> next = temp1 -> next;
    temp1 -> next = temp;
}
int main()
{
    head = NULL;
    Insert(2,1);
    Insert(3,1);
    Insert(99,3);
    Insert(4,2);
    Insert(5,3); // 3, 4, 5, 99, 2 
    Print(); // 1st call
    Delete(2);
    Delete(3); // 3,5,2
    Print(); // 2nd call
    return 0;
}

问题是,根据我的配置,第一次调用print函数产生4,5,2,99,而不是3,4,5,2,99。第二个呼叫显示5,99。

问题出在你的打印函数中,试试这个:

void Print()
{
    cout << "The List is:";
    Node* temp = head;
    while (temp != NULL)
    {
        cout << " " << temp->data;
        temp = temp->next;
    }
}

你需要打印直到temp本身不是NULL
在c++中,我建议使用nullptr而不是NULL

在print函数中,while循环中的两行是颠倒的。您将指针移动到下一个元素,然后打印,因此您永远不会打印第一个元素。你的函数必须像这样:

void Print()
{
    cout << "The List is:" ;
    Node* temp = head;
    while (temp -> next != NULL)
    {
        cout << " " << temp -> data;
        temp = temp -> next;
    }
}