剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 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){
struct ListNode* pre=NULL;//转完后开头为NULL嘛
struct ListNode* cur=head;
while(cur!=NULL){
struct ListNode* next=cur->next;
cur->next=pre;//不是pre=cur->next!!!要使next指向pre!!
pre=cur;
cur=next;
}
return pre;//此时cur为NULL,题目要求返回值开头为5.
}//动画演示很清晰.