定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
首先定义三个节点,pre , cur, temp;
/**
Definition for singly-linked list.
struct ListNode {
int val;
-
struct ListNode *next;
- };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* pre = NULL;
struct ListNode* cur = head;
struct ListNode* temp = NULL;
if(head == NULL || head->next == NULL)
return head;
while(cur != NULL) {
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}