往有序链表的插入元素

在有序链表中插入元素时,最好设置两个指针,一前一后,后面指针负责比较大小,前面的指针负责插入操作。

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

struct vNode {
    int value;
    struct vNode* next;
};


struct vNode* insertIntoSortedList(struct vNode* head,int value){

    struct vNode* node = (struct vNode*)malloc(sizeof(struct vNode));
    struct vNode *p,*q;

    node->value = value;
    node->next = NULL;

    if(head==NULL){ //空链表
        return node;
    }

    if(head->value >= value){ //第一个元素就比value大
        node->next = head;
        return node;
    }

    p = head->next;
    q = head;

    while(p!=NULL && p->value<value){//遍历,直到遇到一个不小于自身的
        q = p;
        p = p->next;
    }

    node->next = p;  //插入操作
    q->next = node;

    return head;
}


int _tmain(int argc, _TCHAR* argv[]){
    //测试代码
    struct vNode* v1 = (struct vNode*)malloc(sizeof(struct vNode));
    struct vNode* v3 = (struct vNode*)malloc(sizeof(struct vNode));
    struct vNode* v5 = (struct vNode*)malloc(sizeof(struct vNode));
    struct vNode* v7 = (struct vNode*)malloc(sizeof(struct vNode));
    struct vNode* v9 = (struct vNode*)malloc(sizeof(struct vNode));

    v1->next = v3;v1->value = 1;
    v3->next = v5;v3->value = 3;
    v5->next = v7;v5->value = 5;
    v7->next = v9;v7->value = 7;
    v9->next = NULL;v9->value = 9;

    v1 = insertIntoSortedList(v1,98);

    while(v1!=NULL){
        printf("%d ",v1->value);
        v1 = v1->next;
    }
    printf("\n");

    return 0;
}

你可能感兴趣的:(链表插入)