PTA删除单链表偶数节点


创建链表,返回头节点。

创建头指针,并分配内存空间,头指针的下一个节点为空。

创建操作指针,指向头节点。while循环录入数据,并注意每次要设置操作指针的下一个

节点为空。

删除函数,将头节点单拿出来考虑。for遍历链表节点,while判断删除。

#include <stdio.h>
#include <stdlib.h>
#include<iostream>
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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM