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