jeudi 23 décembre 2021

how to sort letters followed by its position to create a word using linked list in c++

my program is for sorting a letters entered by the user and each letter is followed by its position to create a word using linked list " the word should be ended by -1 to stop insertion". my problem is when I enter the input nothing happen after that I think the problem is at the function printList(Node* head) put I cant get it .

include <iostream>
using namespace std;

/* Link list node */
class Node
{
public:
    int data;
    char x;
    Node* next;
    void sortedInsert(Node** head_ref, Node* new_node);
    Node* newNode(int new_data);
    void printList(Node* head);
    ~Node() {};
};

/* function to insert a new_node
in a list. Note that this
function expects a pointer to
head_ref as this can modify the
head of the input linked list
(similar to push())*/
void Node::sortedInsert(Node** head_ref, Node* new_node)
{
   
        Node* a = new Node();
    // Advance s to index p.


    Node* current;
    // Special case for the head end 
    if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
    {
        new_node->next = *head_ref;
        *head_ref = new_node;
    }
    else
    {
        // Locate the node before the point of insertion 
        current = *head_ref;
        while (current->next != NULL && current->next->data < new_node->data)
        {
            current = current->next;
        }
        new_node->next = current->next;
        current->next = new_node;
    }
}

/* BELOW FUNCTIONS ARE JUST
UTILITY TO TEST sortedInsert */

/* A utility function to
create a new node */
Node* newNode(char x, int new_data)
{
    /* allocate node */
    Node* new_node = new Node();

    /* put in the data */
    new_node->data = x;
    new_node->data = new_data;
    new_node->next = NULL;

    return new_node;
}

/* Function to print linked list */
void Node::printList(Node* head)
{
    Node* temp = head;
    Node* temp2 = head;
    while (temp != NULL) {
        cout << temp->data << temp2->data << " ";
        temp = temp->next;
        temp2 = temp2->next;
    }
}

int main()
{
    /* string s;
     cout << " enter the letters to sort it : " << endl;
     cin >> s;
     sortString(s);
     cout << endl;*/

    long nums[1000];
    char x[1000];
    cout << " enter exprission followed by its positin  to sort it 'enter -1 to  end it' : ";
    for (int i = 0; i < 1000; i++)
    {
        for (int j = 0; j < 1000; j++)
        {
            cin >> x[i] >> nums[j];
            if (nums[j] == -1)
                break;
            Node* head = NULL;
            Node* new_node = newNode(x[i], nums[j]);
            sortedInsert(&head, new_node);


        }
        Node* head = NULL;
        cout << "Created Linked List\n";
        printList(head);
    }
    return 0;
}


Aucun commentaire:

Enregistrer un commentaire