反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
if(head == NULL || head -> next == NULL)
return head;
struct ListNode *pre, *cur;
pre = NULL;
cur = head;
while(cur != NULL){
struct ListNode *nex;
nex = cur -> next;
cur -> next = pre;
pre = cur;
cur = nex;
}
return pre;
}
本文详细解析了如何通过迭代方式实现单链表的反转。从输入的链表开始,逐步展示如何将每个节点的指向逆转,最终得到完全反转的链表。通过具体的代码示例,帮助读者理解这一经典数据结构操作的实现细节。
199

被折叠的 条评论
为什么被折叠?



