原有单链表1->2->3->4->5->NULL 反转后的链表: 5->4->3->2->1->NULL 用c语言写出完整代码
时间: 2024-06-13 21:03:48 浏览: 103
链表编程-链表-C语言
抱歉,根据提供的引用内容,代码实现是用C++语言写的,而不是C语言。以下是用C++语言实现的代码:
```c++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = NULL;
ListNode* tmp;//用来保存cur->next
while(cur != NULL) {
tmp = cur->next;
cur->next = pre;//结点指向反转
pre = cur;
cur = tmp;
}
return pre;
}
};
```
如果您需要用C语言实现反转单链表的代码,可以参考以下代码:
```c
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *pre = NULL, *cur = head, *tmp;
while (cur != NULL) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
```
阅读全文