leetcode第83题-Remove Duplicates from Sorted List

来源:互联网 发布:python datetime函数 编辑:程序博客网 时间:2024/04/29 21:22

这道题与实现数组中的删除重复元素类似。我们来看一下具体的过程,首先要判断是否为空(在这个上面吃了大苦头),删除下一个相同的元素的时候要定义一个tmp元素,再free掉即可。


#include<stdio.h>#include<stdlib.h>struct ListNode{int val;ListNode *next;};ListNode *deleteDuplicates(ListNode *head) {if (head) {        struct ListNode *p = head;while (p->next) {if (p->val != p->next->val) {p = p->next;}else {struct ListNode *tmp = p->next;p->next = p->next->next;free(tmp);}}}return head;}int main(){int n;while(scanf("%d",&n)!=EOF){ListNode *head=(ListNode *)malloc(sizeof(ListNode));ListNode *p=head;p->next=NULL;for(int i=0;i<n;i++){int tmp;scanf("%d",&tmp);ListNode *q=(ListNode *)malloc(sizeof(ListNode));q->val=tmp;p->next=q;p=q;p->next=NULL;}ListNode *afterHead=deleteDuplicates(head->next);while(afterHead){printf("%d ",afterHead->val);afterHead=afterHead->next;}printf("\n");}return 0;}


1 0
原创粉丝点击