题目链接:https://leetcode-cn.com/problems/reverse-linked-list/
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
思路:假设链表:1 ,2,3,4,5,用三个指针,在原链表上依次把1->NULL, 2->1 3->2.....
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* curr = head;
while (curr) {
struct ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
还有一种思路就是重新创建一个链表,然后把原链表按照头插的方式,插入新开的链表
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *newhead=NULL;
struct ListNode* cur=head;
while(cur){
struct ListNode *next=cur->next;
cur->next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}