求带头结点的单链表的长度
时间: 2024-05-05 22:17:16 浏览: 13
带头结点的单链表的长度为链表中节点的个数,不包括头结点。因此,需要遍历整个链表,统计节点数即可。具体实现可参考以下代码:
```python
def get_length(head):
"""
统计带头结点的单链表的长度
"""
# 初始化节点数为0
count = 0
# 遍历链表,统计节点数
p = head.next # p指向第一个节点
while p is not None:
count += 1
p = p.next
return count
```
其中,`head`为带头结点的单链表的头结点,`head.next`指向第一个节点。遍历链表时,从第一个节点开始,每遍历一个节点,节点数加1,直到遍历完整个链表。最后返回节点数即可。
相关问题
带头结点单链表就地逆置
很高兴为您解答关于带头结点单链表就地逆置的问题。带头结点单链表的就地逆置可以通过从首节点开始反转每一个节点的指向,直到链表末尾完成。这里给出一个简单实现的C++代码:
```C++
#include<iostream>
using namespace std;
class ListNode{
public:
int val;
ListNode* next;
ListNode(){}
ListNode(int x): val(x), next(NULL){}
};
ListNode* reverseList(ListNode* head){
if(head==NULL || head->next==NULL) return head;
ListNode* pre = head;
ListNode* cur = head->next;
ListNode* nxt;
pre->next = NULL;
while(cur!=NULL){
nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
int main(){
int n;
cin>>n;
ListNode* head = new ListNode(0);
ListNode* p = head;
for(int i=0;i<n;i++){
int x; cin>>x;
ListNode* node = new ListNode(x);
p->next = node;
p = p->next;
}
head = reverseList(head);
p = head->next;
while(p!=NULL){
cout<<p->val<<" ";
p = p->next;
}
cout<<endl;
return 0;
}
```
该程序首先定义了一个ListNode类作为单链表的节点,然后定义了一个reverseList函数对带头结点的链表进行就地逆置。在main函数中,程序首先读入链表的长度n以及每个节点的值,然后通过一个循环将链表构建完成。接下来,我们对链表进行就地逆置,最后按照逆序输出每个节点的值。希望我的回答能够帮助到您,如有疑问,请随时追问。
建立两个带头结点单链表
好的,我来给你写一下建立两个带头结点单链表的代码。这里假设链表中存储的元素为整型数。
```c++
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *createList(){
ListNode *head = new ListNode(0); // 头结点
ListNode *cur = head;
int n;
cout << "输入链表长度:";
cin >> n;
for(int i=0; i<n; i++){
int x;
cin >> x;
ListNode *node = new ListNode(x);
cur->next = node;
cur = node;
}
return head;
}
int main(){
ListNode *list1 = createList();
ListNode *list2 = createList();
return 0;
}
```
这个程序会提示你输入两个链表的长度,然后分别输入每一个节点的值,最后返回两个带头结点的链表头指针 list1 和 list2。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)