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

来源:互联网 发布:蜂窝移动网络搜索定位 编辑:程序博客网 时间:2024/06/04 18:56

习题 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;    }}
阅读全文
0 0