#include <stdio.h> #include <stdlib.h>
typedef int ElemType;
typedef struct LNode { ElemType data; struct LNode *next; } LNode, *LinkList;
void list_tail_insert(LNode *&L) { ElemType x; L = (LinkList) malloc(sizeof(LNode)); L->next = NULL; scanf("%d", &x); LNode *s, *r = L; while (x != 9999) { s = (LinkList) malloc(sizeof(LNode)); s->data = x; r->next = s; r = s; scanf("%d", &x); } r->next = NULL; }
LinkList getElem(LinkList L, int pos) { int i = 0; if (pos < 0) { return NULL; } while (L && i < pos) { L = L->next; i++; } return L; }
bool ListFrontInsert(LinkList L, int pos, ElemType e) { LinkList p = getElem(L, pos - 1); if (NULL == p) { return false; } LinkList q; q = (LinkList) malloc(sizeof(LNode)); q->data = e; q->next = p->next; p->next = q; return true; }
void print_linklist(LinkList L) { L = L->next; while (L != NULL) { printf("%d", L->data); L = L->next; if(L != NULL){ printf(" "); } } printf("\n"); }
int main() { LinkList L; bool ret; list_tail_insert(L); print_linklist(L); ret = ListFrontInsert(L, 2, 99); if (ret) { printf("insert success!\n"); print_linklist(L); } else { printf("defate success!\n"); } return 0; }
|