啊哈算法-链表

链表通过结构体(含有数据、结构体指针)来组成。可以方便地查找、删除、修改和插入元素。

练习,写了一个升序排序的链表。写得很复杂,以后有机会写个精简的。

#include<stdio.h>
#include<stdlib.h> 
typedef struct node{
    struct node *next=NULL;
    int data;
}New;
int main(){
    New *head,*nw,*p,*p_2;
    int n,tem;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&tem);
        nw=(New*)malloc(sizeof(New));
        nw->data=tem;
        nw->next=NULL;
        if(i==0) head=nw;
        else{
            p=head;
            if(p->next==NULL){//第二个数 
                if(p->data<tem) p->next=nw;
                else{
                    nw->next=p;
                    head=nw;
                }
            }
            else{//链表长度大于等于二 
                p_2=p->next;
                while(p_2->next!=NULL && tem>p_2->data ){
                    p=p->next;
                    p_2=p->next;
                }
                if(p==head){
                    if(p->data>tem){//nw成为链表头    
                        nw->next=p;
                        head=nw;
                    }
                    else if(p_2->data<tem){//nw成为链表第三节点 
                        p_2->next=nw;
                    }
                    else{//nw成为链表第二节点 
                        p->next=nw;
                        nw->next=p_2;
                    }
                }
                else if(p_2->next==NULL){
                    if(tem>p_2->data) p_2->next=nw;//nw成为链表尾 
                    else {//nw成为倒数第二节点 
                        p->next=nw;
                        nw->next=p_2;
                    }
                }
                else{//nw在链表中间 
                    p->next=nw;
                    nw->next=p_2;
                }
            }
        }
    }
    p=head;
    while(p!=NULL){
        printf("%d ",p->data);
        p=p->next;
    }
    return 0;
} 

 正好今天有个题目写链表 练手精简了一下

#include <stdio.h>
#include<malloc.h>
typedef struct Node{
    int data;
    struct Node *next;
}New;
int main()
{
    int n,tem;
    New *head=NULL,*p;
    scanf("%d",&n);
    while(n--){
        scanf("%d",&tem);
        New *node=(New*)malloc(sizeof(New));
        node->data=tem;
        node->next=NULL;
        if(head==NULL) head=node;
        else{
            p=head;
            if(tem<p->data){//换头 
                node->next=p;
                head=node;
            }
            else{
                while(p->next!=NULL && p->next->data<tem){
                    p=p->next;
                }
                if(p->data<tem && p->next==NULL) p->next=node;
                else{
                    node->next=p->next;
                    p->next=node;
                }
            }
        }
    }
    p=head;
    while(p!=NULL){
        if(p==head) printf("%d",p->data);
        else printf(" %d",p->data);
        p=p->next;
    }
    return 0;
}

 

posted @ 2021-12-14 00:00  m2on  阅读(53)  评论(0编辑  收藏  举报