(c語言實現)刪除有序連結串列中重複出現的元素

Catherine_嘖嘖嘖發表於2020-09-25

題目要求:

給出一個升序排序的連結串列,刪除連結串列中的所有重複出現的元素,只保留原連結串列中只出現一次的元素。

例如:

給出的連結串列為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,使連結串列保持連線
				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); 
} 

相關文章