Sortare liste

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
david_stelian
Junior
Junior
Posts: 20
Joined: 13 Sep 2014, 22:35
Judet: Dolj

Sortare liste

Post by david_stelian » 01 Aug 2015, 17:41

In codul de mai jos am incercat sa fac sortarea unei liste simplu inlntuite.
Ma puteti ajuta ? Nu inteleg unde gresesc.

Code: Select all

#include <iostream>
#include <conio.h>
using namespace std;

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

void bubbleSort(struct node *);
void swap(struct node*, struct node*);
void printList(struct node*);

int main ()
{
    struct node *new_node, *a, *b;
    struct node *head = NULL;
    struct node *temp;
    char caracter = '1';
    while (caracter == '1')
    {
        new_node = new node;
        cout << "\n Introduceti un element : ";
        if (head == NULL)
        {
            cin >> new_node->info;
            head = temp = new_node;
        }
        else
        {
            cin >> new_node->info;
            temp->next = new_node;
            temp = new_node;
        }
        cout << "\n Vreti sa continuati (Apasa \"1\" sau \"0)\": ";
        caracter = getche();
        cout << endl;
    }
    temp->next = NULL;
    printList(head);
    bubbleSort(head);
    swap(a, b);
    printList(head);
    return 0;
}

void printList(struct node *head)
{
    struct node *temp;
    temp = head;
    cout << endl;
    while (temp!=NULL)
    {
        cout << " " << temp->info << " ->";
        temp = temp->next;
    }
    cout << " NULL";
    cout << endl;
}

void bubbleSort(struct node *head)
{
    int swapped, i;
    struct node *ptr1;
    struct node *lptr = NULL;
    if (ptr1 == NULL)
        return;
    do
    {
        swapped = 0;
        ptr1 = head;
        while (ptr1->next != lptr)
        {
            if (ptr1->info > ptr1->next->info)
            {
                swap(ptr1, ptr1->next);
                swapped = 1;
            }
            ptr1 = ptr1->next;
        }
        lptr = ptr1;
    }
    while (swapped);
}

void swap(struct node *a, struct node *b)
{
    int temp;
    temp = a->info;
    a->info = b->info;
    b->info = temp;
}



Post Reply