創建鏈表,返回頭節點。
創建頭指針,並分配內存空間,頭指針的下一個節點為空。
創建操作指針,指向頭節點。while循環錄入數據,並注意每次要設置操作指針的下一個
節點為空。
刪除函數,將頭節點單拿出來考慮。for遍歷鏈表節點,while判斷刪除。
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
#include <stdlib.h>
#include<iostream>
using namespace std;
struct ListNode {
int data;
struct ListNode* next;
};
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");
}
{
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;
{
struct ListNode* head;
head = createlist();
head = deleteeven(head);
printlist(head);
head = deleteeven(head);
printlist(head);
return 0;
}
}