1、删除list中的一个节点,给定位置为i
typedef struct _list_t
{ struct _list_t *next; int data;
}list; void delete_node(list *head, int i)
{list *p = head, *q = NULL;int j = 0;if ((NULL == head) || (0 >= i)){return ;}while ((NULL != p) && (j < i-1)){j++;p = p->next;}if ((NULL != p) && (NULL != p->next)){q = p->next;p->next=q->next;free(q);q = NULL;}
}
2、给定元素key,根据key来删除对应的节点
- #include<iostream>
- using namespace std;
- typedef struct node
- {
- int number;
- struct node *next;
- }Node;
- Node *Delete(Node *head,int key)
- {
- Node *node1=head;
- Node *node2=NULL;
- if (head==NULL)
- {
- return NULL;
- }
- else
- {
- if (node1->number==key)
- {
- head=head->next;
- free(node1);
- return head;
- }
- else
- {
- while (node1!=NULL)
- {
- node2=node1;
- node2=node2->next;
- if (node2->number==key)
- {
- node1->next=node2->next;
- free(node2);
- break;
- }
- node1=node1->next;
- }
- return head;
- }
- }
- }