链表的定义:用一组任意的存储单元存储线性表的数据元素。
注意:存储单元可以是连续的,也可以是不连续的
链表的分类:
静态链表:
动态链表:
leetcode203
删除链表中的元素的时候,
// 对原链表操作
struct ListNode* removeElements(struct ListNode* head, int val) {struct ListNode *tmp; // 存放临时节点,while( head != NULL && head->val == val) // 若链表中的元素 [1,1,1,1,1] 删除的头节点{tmp = head;head = head->next;free(tmp); // 要释放的元素}struct ListNode * curt = head; // 删除的元素并不会改变头节点while(curt != NULL && (tmp = curt->next)){ if(tmp->val == val) // 若cur->next的值等于val{ curt->next = tmp->next; // 改变链表的前驱, 将cur->next设置为cur->next->next并删除cur->nextfree(tmp);} else {curt = curt->next;} }return head;
}// 构造一个虚拟头节点
struct ListNode* removeElements(struct ListNode* head, int val) {struct ListNode* new_head= (struct ListNode*)malloc(sizeof(struct ListNode));new_head->next = head; // 为head构造一个虚拟节点的前驱节点struct ListNode *cur = new_head; // 将当前节点指向headwhile(cur->next != NULL){if(cur->next->val == val){struct ListNode *tmp = cur->next;cur->next = cur->next->next;free(tmp);}else{cur = cur->next;}}head = new_head->next;free(new_head);return head;
}