题解 | #删除链表中重复的结点#

删除链表中重复的结点

https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=&judgeStatus=3&tags=&title=&gioEnter=menu

只适合有序,无序链表需要用哈希表

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
      if (pHead == nullptr || pHead->next == nullptr) {
        return pHead;
      }
      
      auto head = std::make_unique<ListNode>(-1);
      head->next = pHead;
      ListNode *pre = head.get();
      ListNode *cur = pHead->next;
      
      while (cur) {
        if (cur->val != pre->next->val) {
          cur = cur->next;
          pre = pre->next;
        } else {
          ListNode *tmp = pre->next;
          //  跳过重复结点
          while (tmp && tmp->val == cur->val) {
            tmp = tmp->next;
          }
          
          cur = tmp;
          tmp = pre->next;
          pre->next = cur;
          
          ListNode *nex = tmp->next;
          
          //  删除结点
          while (nex != cur) {
            delete tmp;
            tmp = nex;
            nex = nex->next;
          }
          
          delete tmp;
          
          if (cur) {
            cur = cur->next;
          }
        }
      }
      
      return head->next;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务