问题描述:翻转一个链表
样例:给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
实现思路:将第一个结点指向空,然后将后续结点的指针改变方向,即让当前结点的后继指向当前结点,当前结点指向它的前驱。
实现代码:
* Definition of ListNode
*
* class ListNode {
* public:
* int val;
* ListNode *next;
*
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
ListNode *pre=NULL;
while(head!=NULL){
ListNode *temp=head->next;
head->next=pre;
pre=head;
head=temp;}
return pre;
}// write your code here
};
做题感想:对我来说,我感觉这个题挺绕的,让同学讲了好几次。做完以后有想到这个题其实可以新建一个链表,然后用头插法来解决。