创建链表,返回头节点。
创建头指针,并分配内存空间,头指针的下一个节点为空。
创建操作指针,指向头节点。while循环录入数据,并注意每次要设置操作指针的下一个
节点为空。
删除函数,将头节点单拿出来考虑。for遍历链表节点,while判断删除。
#include
#include
#include
using namespace std;
struct ListNode {
int data;
struct ListNode* next;
};
struct ListNode* createlist()
{
ListNode* head = new ListNode;
head->next = NULL;
ListNode* temp = head;
int n; cin >> n;
while (n!=-1)
{
temp->data = n;
temp->next = new ListNode;
temp = temp->next;
cin >> n;
temp->next = NULL;//一定要加!!!!!
}
return head;
}
struct ListNode* deleteeven(struct ListNode* head)
{
for (ListNode* temp = head; temp->next != NULL; temp = temp->next)
{
while(temp->next->data % 2 == 0)
{
ListNode* shanchu = temp->next;
temp->next = shanchu->next;
delete shanchu;
}
}
if (head && head->data % 2 == 0)
{
ListNode* shanchu = head;
head = shanchu->next;
delete shanchu;
}
return head;
}
void printlist(struct ListNode * head)
{
struct ListNode* p = head;
while (p&&p->next) {
cout << p->data << " ";
p = p->next;
}
printf("\n");
}
int main()
{
struct ListNode* head;
head = createlist();
head = deleteeven(head);
printlist(head);
return 0;
}