#include<iostream> #include<stack> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* cur = head; ListNode* beginDelete = NULL;//要删除的起始节点 ListNode* last = NULL;//不被删除的最后一个节点 ListNode* temp = NULL; while (cur){ beginDelete = cur; while (cur->next){ if (beginDelete->val == cur->next->val) cur = cur->next; else break; } if (beginDelete == cur){ head = cur; break; }else{ cur = cur->next; while (beginDelete != cur){ temp = beginDelete; beginDelete = beginDelete->next; delete temp; } beginDelete = NULL; head = cur; } }//找出第一个没有重复的 如1 1 2 2 3 4 5 5 找出3;1 3 3 4 找出1 while (cur){ beginDelete = cur; while (cur->next){ if (beginDelete->val == cur->next->val) cur = cur->next; else break; } if (beginDelete == cur){ last = cur; cur = cur->next; }else{ cur = cur->next; while (beginDelete != cur){//删除一个,头结点串接下一个节点 temp = beginDelete; beginDelete = beginDelete->next; last->next = beginDelete; delete temp; } beginDelete = NULL; } } return head; } ListNode* createList(ListNode* head){ int numOfNode; int value; cout << "please input number of listNode:"; cin >> numOfNode; cin >> value; head = new ListNode(value); ListNode* cur = head; for (int i = 1; i < numOfNode; ++i){ cin >> value; ListNode* temp = new ListNode(value); cur->next = temp; cur = temp; } return head; } void printNode(ListNode* head){ ListNode* cur = head; while (cur){ cout << cur->val << " "; cur = cur->next; } cout << endl; } }; int main(){ ListNode* head = NULL; Solution solution; head = solution.createList(head); solution.printNode(head); head = solution.deleteDuplicates(head); solution.printNode(head); system("pause"); return 0; }