题目:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
过程:
1.struct ListNode* next = cur->next;
2.cur->next = newhead;
3.newhead = cur; cur = next;
以此类推:
结束while循环。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
//方法二:头插法
struct ListNode* cur = head;
struct ListNode* newhead = NULL;
while(cur)
{
struct ListNode* next = cur->next;
//头插
cur->next = newhead;
newhead = cur;
//迭代往后走
cur = next;
}
return newhead;
}