递增的整数序列链表的插入

习题 2.4 递增的整数序列链表的插入

今天做了浙大 PAT 数据结构的一道链表题,在此过程中进行了以下几个问题的研究,不过仍然有些疑惑:

  1. 链表结构体构造
  2. 链表节点链接
  3. 链表节点插入
  4. typedef 的使用就是给变量起别名
  5. 将指针作为参数进行传递时,不需要用或者 & 吗???????,今天做的链表指针传递的时候都没有使用 ,不过编译通过了,而 mooc 上课件里却使用了 *
  6. 不要贪图省事就将多步操作合并到一起,这样做如果出错不好找

代码块

/*习题 2.4 递增的整数序列链表的插入*/

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

typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
    ElementType Data;
    PtrToNode   Next;
};
typedef PtrToNode List;


List Read(); /* 细节在此不表 */
PtrToNode CreatNewNode();/*创建新节点*/

void Print(List L); /* 细节在此不表 */

List Insert(List L, ElementType X);

int main()
{
    List L;
    ElementType X;
    L = Read();
    scanf("%d", &X);
    L = Insert(L, X);
    Print(L);

    return 0;
}


List Read()
{
    int N, i;
    PtrToNode LBegin, newNode, preNode, tmp;

    scanf("%d", &N);
    LBegin = CreatNewNode();

    preNode = LBegin;

    while (N) {
        newNode = CreatNewNode();
        scanf("%d", &i);
        preNode->Data = i;/*使用&i  对Data进行中转,可以直接使用&newnode->data吗???*/
        preNode->Next = newNode;
        preNode = newNode;
        newNode->Next = NULL;/*链接各个节点*/
        N--;
    }


    return LBegin;
}

List CreatNewNode()
{
    List newNode;
    newNode = (List)malloc(sizeof(struct Node));

    return newNode;
}

List Insert(List L, ElementType X)
{
    PtrToNode tmp, pre, NodeToInsert;
    pre = L;
    NodeToInsert = CreatNewNode();
    NodeToInsert->Data = X;


    if (X < L->Data) {
        /*数据要插入在链表之前*/
        NodeToInsert ->Next = L;


        return NodeToInsert;
    }

    while (pre) {
        if (X > pre->Data) {
            if (X <= pre->Next->Data) {/*插入在链表中*/
                NodeToInsert->Next = pre->Next;
                pre->Next = NodeToInsert;
                return L;
            }

            else if (pre->Next == NULL) {/*插到链尾*/
                pre->Next = NodeToInsert;
                return L;
            }
        }
        pre = pre->Next;
    }
}

void Print(List L)
{
    PtrToNode pre;
    pre = L;
    while (pre->Next) {
        printf("%d ", pre ->Data);
        pre = pre->Next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值