【LeetCode】Remove Duplicates from Sorted List

题目描述

Remove Duplicates from Sorted List

 

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.


题目分析

去除链表中的重复数字。纯粹的链表操作。
定义两个指针,如果后面那个指针的val和前面的一样,就把后面的删除


代码示例


#include <iostream>
#include <vector>
using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
 };
 
 void printList(ListNode *head,char *name)
{
	printf("%s\n",name);
	while(head != NULL)
	{
		printf("%3d,",head->val);
		head = head->next;
	}
	printf("\n");
}

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head == NULL)	return NULL;
        ListNode *p = head;
        ListNode *q = p->next;
        while(q != NULL)
        {
        	if(p->val == q->val)//把q移除
			{
				p->next = q->next;
				q = p->next; 
			} 
			else
			{
				q = q->next;
				p = p->next;
			}
		}
		return head;
    }
};


/*
vector 在添加过程中会动态的申请内存,元素的位置会动态的调整,所以
不能边创建vector边创建链表,中间指针可能会动。

这里的list需要使用传引用 
*/
ListNode* listCreate(vector<ListNode> &list, int arr[], int n)
{
	if(n <= 0)
		return NULL;
		
	for(int i=0;i<n;i++)
	{
		ListNode tmp(arr[i]);
		list.push_back(tmp);
	}
	
	ListNode *head = &list[0];
	for(int i=1;i<n;i++)
	{
		head->next = &list[i];
		head = head->next;
	}
	head = &list[0];
	return head;
}
void CheckList(ListNode *head,int arr[], int n)
{
	int i = 0;
	for(i = 0;i<n && head != NULL;i++,head=head->next)
	{
		if(head->val != arr[i])
			break;
	}
	if(i != n)
		printf("------------------------failed\n");
	else
		printf("------------------------passed\n");
}

//功能测试,长度为偶数 
void test0()
{
	vector<ListNode> list;
	int arr[10] = {0,1,1,3,3,5,6,7,7,7};
	ListNode *head = listCreate(list,arr, 10);
	printList(head,"head");
	Solution so;
	so.deleteDuplicates(head);
	int arr1[6] = {0,1,3,5,6,7};
	CheckList(head,arr1,6);
	//printList(head,"head");
}

int main(int argc, char *argv[])
{
	test0(); 
	return 0;
}



推荐学习C++的资料

C++标准函数库
在线C++API查询


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值