Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
-----------------------------------------------------------------------------------------------------------------------------------
链表翻转题
可以用O(1)的空间解决,就是新建立两个辅助结点,不占什么空间,然后,其中一个结点指向head,并且,head改为NULL,然后,进行翻转。
注意在循环是,这两个辅助结点的next的变化,不能漏掉,可以画图来辅助理解和检查。
emmm下面的代码不太好理解。用dummy->next指代head就好理解很多了。
C++代码:
不适用dummy.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *p,*q; p = head; head = NULL; while(p){ q = p->next; p->next = head; head = p; p = q; } return head; } };
使用dummy.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *dummy = new ListNode(-1); dummy->next = head; ListNode *p,*q; p = dummy->next; dummy->next = NULL; while(p){ q = p->next; p->next = dummy->next; dummy->next = p; p = q; } return dummy->next; } };
来源:https://www.cnblogs.com/Weixu-Liu/p/10703998.html