删除链表中重复的结点(c++&&go)

/*
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,
返回链表头指针。 例如,链表 1->2->3->3->4->4->5  处理后为 1->2->5
*/
#include <bits/stdc++.h>

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};

class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        if(pHead == nullptr)
            return nullptr;

        ListNode* pNewHead = new ListNode(0);
        ListNode* curNode = pNewHead;

        while (pHead != nullptr)
        {
            if(pHead->next == nullptr && pHead->val != pHead->next->val)
            {
                curNode->next = pHead;
                curNode = curNode->next;
            }

            while (pHead->next != nullptr && pHead->val == pHead->next->val)
            {
                pHead = pHead->next;
            }
            
            pHead = pHead->next;

        }
        return pNewHead;
    }
};

int main()
{
    ListNode* pHead = new ListNode(1);
    ListNode* pNode1 = new ListNode(2);
    ListNode* pNode2 = new ListNode(3);
    ListNode* pNode3 = new ListNode(3);
    ListNode* pNode4 = new ListNode(4);
    ListNode* pNode5 = new ListNode(4);
    ListNode* pNode6 = new ListNode(5);

    pHead->next = pNode1;
    pNode1->next = pNode2;
    pNode2->next = pNode3;
    pNode3->next = pNode4;
    pNode4->next = pNode5;
    pNode5->next = pNode6;

    Solution cSolution;
    cSolution.deleteDuplication(pHead);
    return 1;
}
/*
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,
返回链表头指针。 例如,链表 1->2->3->3->4->4->5  处理后为 1->2->5
*/

package main

type ListNode struct{
   Val int
   Next *ListNode
}


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param pHead ListNode类 
 * @return ListNode类
*/
func deleteDuplication( pHead *ListNode ) *ListNode {
    if pHead == nil {
		return nil
	}

	pNewHead := new(ListNode)
	curNode := pHead

	for pHead != nil{
		if pHead.Next != nil && pHead.Val == pHead.Next.Val {
			curNode.Next = pHead;
			curNode = curNode.Next
		}

		for pHead.Next != nil && pHead.Val == pHead.Next.Val{
			pHead = pHead.Next
		}
		pHead = pHead.Next
	}

	return pNewHead.Next
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值