LeetCode 面试题24. 反转链表

时间:2023-11-24 14:37:20

题目链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

限制:

0 <= 节点个数 <= 5000

 /**
* 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,*cur=head,*tmp;
while(cur){
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=tmp;
}
return pre;
}