題目1181:遍歷鏈表

Problem:


Solution:

題目要求很清楚,先建立一個鏈表,再對鏈表進行類似於冒泡的排序即可
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

struct LNode
{
    int val;
    struct LNode *next;
};
int main()
{
    int n,m;
    LNode *head,*p,*q;

    while (cin >> n)
    {
        head = (LNode*)malloc(sizeof(LNode));
        head -> next = NULL;
        q = head;
        if (n == 0) cout<<endl;
        else
        {
            for (int i = 0;i < n;i++)
            {
                cin >> m;
                p = (LNode*)malloc(sizeof(LNode));
                p -> val = m;
                q -> next = p;
                q = q -> next;
            }
            p -> next = NULL;
        }
        p = head->next;

        while(p!=NULL){
            q=p->next;
            while(q!=NULL){
                if(p->val>q->val){
                    int temp=p->val;
                    p->val=q->val;
                    q->val=temp;
                }
                q=q->next;
            }
            p=p->next;
        }
        while (head->next)
        {
            cout <<head->next->val<< " "  ;
            head = head->next;
        }
    }
    free(head);
    free(p);
    free(q);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章