C语言PTA链表-查找链表最后节点
时间: 2024-06-16 13:00:50 浏览: 24
链表是一种常用的数据结构,它由若干个节点组成,每个节点包含两部分内容:数据和指针。其中数据用来存储具体的信息,而指针则用来连接下一个节点,形成一个链式结构。
在C语言中,链表通常使用结构体来定义。例如下面的代码定义了一个简单的链表节点结构体:
```
struct ListNode {
int val;
struct ListNode *next;
};
```
其中`val`表示该节点存储的整数值,`next`则是指向下一个节点的指针。如果一个节点是最后一个节点,则它的`next`指针应该为`NULL`。
要查找链表的最后一个节点,可以使用循环遍历链表的方式,直到找到最后一个节点为止。具体实现代码如下:
```
struct ListNode* findLastNode(struct ListNode* head) {
if (head == NULL) return NULL;
while (head->next != NULL) {
head = head->next;
}
return head;
}
```
该函数接受一个链表头指针`head`作为参数,返回最后一个节点的指针。在函数内部,我们首先判断链表是否为空,如果是,则直接返回`NULL`;否则我们使用循环遍历链表,直到找到最后一个节点为止,然后返回它的指针。
相关问题
链表-查找链表最后节点函数pta
根据提供的引用内容,以下是一个查找链表最后节点的函数的示例代码:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
def find_last_node(head):
if head is None:
return None
current = head
while current.next is not None:
current = current.next
return current
# 示例链表
head = Node(1)
node2 = Node(2)
node3 = Node(3)
head.next = node2
node2.next = node3
last_node = find_last_node(head)
print("The value of the last node is:", last_node.value) # 输出:The value of the last node is: 3
```
该函数通过遍历链表,直到找到最后一个节点,并返回该节点的值。如果链表为空,则返回None。
C语言-链表-添加到链表尾部
以下是C语言中将新节点添加到链表尾部的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node* next;
};
// 在链表尾部添加新节点
void append(struct Node** head_ref, int new_data) {
// 为新节点分配内存
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; // 用于遍历链表
// 设置新节点的值和下一个节点为NULL
new_node->data = new_data;
new_node->next = NULL;
// 如果链表为空,则将新节点设置为头节点
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
// 遍历链表,找到最后一个节点
while (last->next != NULL) {
last = last->next;
}
// 将新节点添加到链表尾部
last->next = new_node;
return;
}
// 测试代码
int main() {
struct Node* head = NULL; // 初始化链表为空
// 添加节点
append(&head, 1);
append(&head, 2);
append(&head, 3);
// 遍历链表并输出每个节点的值
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)