链表-查找链表最后节点函数pta
时间: 2024-01-04 14:19:31 浏览: 51
根据提供的引用内容,以下是一个查找链表最后节点的函数的示例代码:
```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。
相关问题
高阶-1 链表-查找链表最后节点
要查找链表的最后一个节点,可以使用两个指针来迭代链表。一个指针指向当前节点,另一个指针指向当前节点的下一个节点。当后一个指针为空时,当前指针就指向了最后一个节点。
以下是一个示例代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def find_last_node(head):
if not head:
return None
current = head
while current.next:
current = current.next
return current
```
这个代码中,我们定义了一个链表节点类 ListNode,包含一个值 val 和一个指向下一个节点的指针 next。函数 `find_last_node` 接受链表的头节点作为参数,并返回最后一个节点。
我们从头节点开始,通过迭代将当前节点指针移动到下一个节点,直到遇到最后一个节点(即下一个节点为空)。最后,返回当前节点作为结果。
希望这个回答对你有帮助!如果还有其他问题,请随时提问。
用C语言查找链表最后节点
好的,以下是用 C 语言实现查找链表最后节点的示例代码:
```c
struct Node {
int data;
struct Node* next;
};
struct Node* getLastNode(struct Node* head) {
if (head == NULL) {
return NULL;
}
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
return current;
}
```
其中,Node 是链表节点的结构体,包含一个数据成员和一个指向下一个节点的指针成员。函数 getLastNode 接受一个头节点指针作为参数,返回最后一个节点的指针。函数首先检查头节点是否为 NULL,如果是,则返回 NULL,否则从头节点开始遍历链表,直到找到最后一个节点,并返回该节点的指针。
示例用法:
```c
int main() {
// 创建链表
struct Node* head = malloc(sizeof(struct Node));
head->data = 1;
head->next = NULL;
struct Node* node1 = malloc(sizeof(struct Node));
node1->data = 2;
node1->next = NULL;
head->next = node1;
struct Node* node2 = malloc(sizeof(struct Node));
node2->data = 3;
node2->next = NULL;
node1->next = node2;
// 查找最后一个节点
struct Node* lastNode = getLastNode(head);
printf("Last node data: %d\n", lastNode->data);
// 释放链表内存
free(node2);
free(node1);
free(head);
return 0;
}
```