题目1181:遍历链表

来源:互联网 发布:c4d全局光照优化设置 编辑:程序博客网 时间:2024/05/20 23:34

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;}


0 0
原创粉丝点击