1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
| #include <stdio.h> #include <stdlib.h> #define OK 1 #define ERR 0 #define MAXSIZE 100 typedef int ElemType;
typedef struct Node { ElemType data; struct Node *next; }Node,*LinkedList;
LinkedList LinkedListInit() { Node *L; L = (Node * )malloc(sizeof(Node)); if (L==NULL) { printf("申请内存空间失败."); } L->next=NULL; return L; }
LinkedList LinkedListCreateHead() { Node *Head; Head = (Node *)malloc(sizeof(Node)); Head->next=NULL; ElemType x; while (scanf("%d",&x)!=EOF) { Node *P; P=(Node *)malloc(sizeof(Node)); P->data=x;
P->next=Head->next; Head->next=P; } return Head; }
LinkedList LinkedListCreateTail() { Node *Head; Head = (Node*)malloc(sizeof(Node)); Head->next=NULL;
Node *Tail; Tail=Head;
ElemType x; while (scanf("%d",&x)!=EOF) { Node *P = (Node *)malloc(sizeof(Node)); P->data=x; Tail->next=P; Tail=P; } Tail->next=NULL; return Head; }
LinkedList LinkedListInsert(LinkedList L,int i,ElemType x) { Node *pre; pre = L; int temp=0; for (temp=1;temp<i;temp++) pre=pre->next; Node *P = (Node *)malloc(sizeof(Node)); P->data = x; P->next=pre->next; pre->next=P; return L;
}
LinkedList LinkedListDel(LinkedList L,ElemType x) { Node *pre,*p; p=L->next; while (p->data!=x) { pre=p; p=p->next; } pre->next=p->next; free(p); return L; }
void LinkedListShow(LinkedList L) { LinkedList temp; int i=0; for(i=1,temp = L->next; temp != NULL; i++,temp = temp->next) printf("(%d)->%d ",i,temp->data); printf("\n"); } int main() {
LinkedList L; printf("请输入单链表的数据:\n"); L=LinkedListCreateTail(); printf("该链表为:\n"); LinkedListShow(L);
int i; ElemType x; printf("请输入插入数据的位置和值,用空格隔开:\n"); scanf("%d %d",&i,&x); LinkedListInsert(L,i,x); printf("该链表为:\n"); LinkedListShow(L);
printf("请输入要删除的元素的值:"); scanf("%d",&x); LinkedListDel(L,x); printf("该链表为:\n"); LinkedListShow(L); return 0; }
C
|