(c语言实现)删除有序链表中重复出现的元素

题目要求:

给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。

例如:

给出的链表为1→2→3→3→4→4→5, 返回1→2→5.
给出的链表为1→1→1→2→3, 返回2→3.

思路:

代码:


#include<stdio.h>
#include<stdlib.h>
typedef struct ListNode{
	int data;
	struct ListNode *next;
	 
}list;

list *creatlist()
{//创建链表 
	list *head,*current,*now;
	
	now = (list*)malloc(sizeof(list));
	scanf("%d",&now->data);
	if (now->data == -1)
	{
		return NULL;
	}
	head = current = now;
	while (current->data != -1) 
	{
		now = (list*)malloc(sizeof(list));
		scanf("%d",&now->data);
		if (now->data == -1)
		{
			current->next = NULL;
			break; 
		} 
		else
		{
			current->next = now;
			current = current->next;
		}
		 
	}
	
	return head; 
}
void printlist(list *head)
 {//打印链表 
	list *p = head;
	
	while (p)
	{
		printf("%d ",p->data);
		p = p->next;
	}
}
list *deletelist(list *head)
{
	list *pre = NULL,*curr = head,*next;
	
	if(head == NULL || head->next == NULL)//头结点为空或者链表只有一个数 
		return head; 
	
	while (curr)
	{
		next = curr->next;
		
		if ((next != NULL) && (curr->data == next->data))
		{
			
			int x = curr->data;
			list* temp = curr;

			while ((temp != NULL) && (temp->data == x))
			{
				next = temp->next;
				temp = next;
			}

			if (pre == NULL)    
				head = next;
			else              
				pre->next = next;

			curr = next;
		}
		else {
			pre = curr;
			curr = next;
		}
	} 
	
	return head;
} 
int main(void)
{
	list *head,*head_2;
	
	head = creatlist();
	head_2 = deletelist(head);
	printlist(head_2); 
} 
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页