移除链表元素
1.问题
给你一个链表的头节点
head
和一个整数val
,请你删除链表中所有满足Node.val == val
的节点,并返回 新的头节点 。
2.代码实现:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int SLTDataType;
typedef struct SListnode
{
SLTDataType val;
struct SListnode* next;
}ListNode;
ListNode* createNode(SLTDataType val)
{
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
if (newnode == NULL)
{
perror("malloc");
exit(1);
}
newnode->val = val;
newnode->next = NULL;
return newnode;
}
struct ListNode* removeElements(struct ListNode* head, int val)
{
ListNode* pur = head;
ListNode* newhead, *newtail;//创建新链表
newhead = newtail = NULL;//表头 表尾初始化
while (pur)
{
if (pur->val != val)
{
if (newhead == NULL)
{
newhead = newtail = pur;
}
else
{
newtail->next = pur;
newtail = newtail->next;
}
}
pur = pur->next;
}
if (newtail)
{
newtail->next=NULL;
}
return newhead;
}
int main()
{
ListNode* node1, * node2, * node3, * node4, * node5, * node6, * node7;
node1 = createNode(1);
node2 = node1->next = createNode(2);
node3 = node2->next = createNode(6);
node4 = node3->next = createNode(3);
node5 = node4->next = createNode(4);
node6 = node5->next = createNode(5);
node7 = node6->next = createNode(6);//创建一个链表
ListNode* newhead = removeElements(node1, 6);//移除链表元素:6
while (newhead)
{
printf("%d ", newhead->val);
newhead = newhead->next;
}
return 0;
}