【发布时间】:2021-02-21 08:08:31
【问题描述】:
我正在检查单链表长度的奇偶校验:
- 如果很奇怪,我必须删除第一个节点;
- 如果是偶数,我必须删除最后一个节点。
我能够找出奇偶校验但无法删除相关节点。
鉴于我还必须使用签名void sil(struct node **head),我应该更改什么并添加到我的代码中?
// C program to check length
// of a given linklist
#include<stdio.h>
#include<stdlib.h>
// Defining structure
struct Node
{
int data;
struct Node* next;
};
// Function to check the length of linklist
int LinkedListLength(struct Node* head)
{
while (head && head->next)
{
head = head->next->next;
}
if (!head)
return 0;
return 1;
}
// Push function
void push(struct Node** head, int info)
{
// Allocating node
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
// Info into node
node->data = info;
// Next of new node to head
node->next = (*head);
// head points to new node
(*head) = node;
}
// Driver function
int main(void)
{
struct Node* head = NULL;
// Adding elements to Linked List
push(&head, 4);
push(&head, 5);
push(&head, 7);
push(&head, 2);
push(&head, 9);
push(&head, 6);
push(&head, 1);
push(&head, 2);
push(&head, 0);
push(&head, 5);
push(&head, 5);
int check = LinkedListLength(head);
// Checking for length of
// linklist
if(check == 0)
{
printf("Even\n");
}
else
{
printf("Odd\n");
}
return 0;
}
【问题讨论】:
-
这个问题有很多很好的答案。 Using pointers to remove item from singly-linked list