Leetcode206.反转链表(C语言)
数据结构-链表:算法与数据结构参考
题目:
反转一个单链表,例如:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路:
先存储cur->next进行拆分;将拆分后的插入新链表头部(头插法)
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL && head == NULL) return head;
struct ListNode *pre = NULL;
struct ListNode *cur = head;
while(cur != NULL){
struct ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}