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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
| #include <stdio.h> #include <stdlib.h>
typedef struct Point_node { int data; struct Point_node *next;
} LinkList;
LinkList *Creat(int n); void Display(LinkList *head); LinkList *Find(LinkList *head, int pos); LinkList *Change(LinkList *head, int pos, int data); int Delete(LinkList *head, int pos); LinkList *Insert_Backward(LinkList *head, int pos, int data); LinkList *Insert_Forward(LinkList *head, int pos, int data);
int main() { int n; printf("请输入节点数:"); scanf("%d", &n); LinkList *head = Creat(n);
Display(head);
int position = 0, data = 0;
printf("\n请输入需要插入节点的位置与值(向前):"); scanf("%d %d", &position, &data); printf("%d", Insert_Forward(head, position - 1, data)->data); getchar(); }
LinkList *Creat(int n) { LinkList *head = NULL, *end = NULL, *node = NULL; printf("请输入节点数据:"); for (int i = 0; i < n; i++) { if (head == NULL) { head = (LinkList *)malloc(sizeof(LinkList)); head->next = NULL; end = head; scanf("%d", &end->data); } else { node = (LinkList *)malloc(sizeof(LinkList)); node->next = NULL; scanf("%d", &node->data); end->next = node; end = node; } } return head; }
void Display(LinkList *head) { while (1) { if (head == NULL) { break; } else { printf("%d ", head->data); head = head->next; } } }
LinkList *Find(LinkList *head, int pos) { if (head == NULL) { printf("\n节点为空"); return NULL; } if (pos < 0) { printf("\n非法位置!"); return NULL; } int i; for (i = 0; i < pos; i++) { head = head->next; if (head == NULL) { printf("\n位置越界!"); return NULL; } } return head; } LinkList *Change(LinkList *head, int pos, int data) { LinkList *p = Find(head, pos); p->data = data; return p; } int Delete(LinkList *head, int pos) { int data = NULL; LinkList *p = Find(head, pos - 1), *temp;
if (p == NULL) { printf("\n删除失败!"); return NULL; } temp = p->next; p->next = temp->next; data = temp->data; free(temp); return data; }
LinkList *Insert_Backward(LinkList *head, int pos, int data) { LinkList *p = Find(head, pos); if (p == NULL) { printf("\n插入失败!"); return NULL; } LinkList *node = (LinkList *)malloc(sizeof(LinkList)); node->data = data; node->next = p->next; p->next = node; return node; }
LinkList *Insert_Forward(LinkList *head, int pos, int data) { LinkList *p = Find(head, pos - 1);
if (p == NULL) { printf("\n插入失败!"); return NULL; } LinkList *node = (LinkList *)malloc(sizeof(LinkList)); node->data = data; node->next = p->next; p->next = node; return node; }
|