剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
注意:本题与主站 206 题相同
解题思路:
- 链表的头插法
/**
* 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 = NULL; //pre指向空节点
struct ListNode *cur = head; //cur指向头结点head
struct ListNode *next = head->next; //在断开链之前,暂存后继节点
while (next!=NULL){ // 如果head为空就不会进入循环
cur->next = pre; //断开现在的链,重新指向
pre = cur; //pre 暂存 cur,作为cur下一步的前继节点
cur = next; //cur 访问下一节点
next = next->next;
}
cur->next = pre; //此时cur指向null,返回cur的前继节点pre
return cur;
}