期末考试题:数据结构期末考试题目---笔记(SYSU)

也不知道为什么考试的时候好像脑子抽了一样,这么简单的一个题目居然慌了神没有写
结果 90分变成了80分???
我的国奖梦啊!!!

当然这也说明我对于指针没有想象中的那么熟悉,导致了我在慌乱的情况下就没有了那么高的水准,这点要检讨。
希望以后看这个博客的其他同学们也要引以为戒。

题目意思:
将一个链表的连续的重复数字给删掉变成一个

就是 1 -> 2 -> 2 -> 3 -> NULL
变成 1 -> 2 -> 3 -> NULL

#include <iostream>using namespace std;struct Node{ int val; Node* next; Node(int v = 0){ val = v; next = NULL; } };void PRINT(Node* head) { Node *cur = head; while (cur != NULL) { cout << cur->val<<" --> "; cur = cur->next; } cout << "NULL\n";} Node* DELETESAME( Node* head ) { int last = 0; Node *cur = head, *pre, *s; while (cur != NULL) { if (cur == head || cur->val != last) { last = cur -> val; pre = cur; cur = cur->next; } else { // delete cur; last 不更新 pre 也不更新 s = cur; pre -> next = cur->next; cur = cur -> next; delete s; s = NULL; } } return head;} int main(){ Node *head = new Node; head->val = 1; Node *cur = head; for (int i = 2; i < 5; ++i) { for (int j = 1; j <= 3; ++j) { cur->next = new Node(i); cur = cur->next; } } PRINT(head); head = DELETESAME(head); PRINT(head);}

相关推荐

相关文章