C++ 删除无头链上所有指定值为x的节点。
- #include
- #include
- #include
- typedef struct app
- {
- int data;
- struct app* next;
- }APP;
- int main()
- {
- int n;
- int node;
- int x;
- while (scanf("%d", &n) != EOF)
- {
- APP* head = NULL, * p = NULL, * newnode = NULL;
- for (int i = 0; i < n; i++)
- {
- scanf("%d", &node);
- if (head == NULL)
- {
- head = (APP*)malloc(sizeof(APP));
- p = head;
- head->data = node;
- head->next = NULL;
- }
- else
- {
- newnode = (APP*)malloc(sizeof(APP));
- newnode->data = node;
- newnode->next = NULL;
- p->next = newnode;
- p = newnode;
- }
- }
-
- scanf("%d", &x);
-
- APP* pre = NULL; //要删节点的前一个节点
- APP* curr = head;// curr当前
- while (curr) {
- if (curr->data == x) {
-
- //分两种情况处理
- if (pre == NULL) {//说明是链首删
- APP* t = curr;
- curr = curr->next;
- free(t);
- head=curr;
- continue;
- }
- else {
- pre->next = curr->next;
- free(curr);
- curr = pre->next;
- }
- }else{//不需要删的遍历下一条
- pre = curr;
- curr = curr->next;
- }
- }
-
-
-
- p = head;
- while (p)
- {
- printf("%d ", p->data);
-
- p = p->next;
- }
- puts("");
-
- }
-
- }