6-8 單連結串列結點刪除 (20 分)

matthew_leung發表於2018-11-08

6-8 單連結串列結點刪除 (20 分)

本題要求實現兩個函式,分別將讀入的資料儲存為單連結串列、將連結串列中所有儲存了某給定值的結點刪除。連結串列結點定義如下:

struct ListNode {
    int data;
    ListNode *next;
};

函式介面定義:

struct ListNode *readlist();
struct ListNode *deletem( struct ListNode *L, int m );

函式readlist從標準輸入讀入一系列正整數,按照讀入順序建立單連結串列。當讀到−1時表示輸入結束,函式應返回指向單連結串列頭結點的指標。

函式deletem將單連結串列L中所有儲存了m的結點刪除。返回指向結果連結串列頭結點的指標。

裁判測試程式樣例:

#include <stdio.h>
#include <stdlib.h>

struct ListNode {
    int data;
    struct ListNode *next;
};

struct ListNode *readlist();
struct ListNode *deletem( struct ListNode *L, int m );
void printlist( struct ListNode *L )
{
     struct ListNode *p = L;
     while (p) {
           printf("%d ", p->data);
           p = p->next;
     }
     printf("\n");
}

int main()
{
    int m;
    struct ListNode *L = readlist();
    scanf("%d", &m);
    L = deletem(L, m);
    printlist(L);

    return 0;
}

/* 你的程式碼將被嵌在這裡 */

輸入樣例:

10 11 10 12 10 -1
10

輸出樣例: 

11 12 
struct ListNode *readlist()
{
	struct ListNode *head, *p, *q;
	head = (struct ListNode*)malloc(sizeof(struct ListNode));
	head->next = NULL;
	p = head;
	while (1)
	{
		q = (struct ListNode*)malloc(sizeof(struct ListNode));
		scanf("%d", &q->data);
		if (q->data == -1)
			break;
		p->next = q;
		p = q;
	}
	p->next = NULL;

	return head;
}
struct ListNode *deletem(struct ListNode *L, int m)
{
	struct ListNode *head, *p, *q;
	head = L, p = L->next, q = L;
	while (p)
	{
		if (p->data == m)
		{
			head->next = p->next;
			free(p);
			p = head->next;
			continue;
		}
		head = head->next;
		p = p->next;
	}
	return q->next;
}

 

 

 

 

 
 
 

相關文章