1.问题描述:翻转一个链表,例如给出一个链表1->2->3->null,翻转后为3->2->1->null
2.思路:
3.代码:
/**
* 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) {
// write your code here
ListNode *dummy=NULL;
while(head!=NULL)
{ ListNode *temp=head->next;
head->next=dummy;
dummy=head;
head=temp;
}
return dummy;
}
};
4.感想:感觉链表的想不出的一些问题画个图之后就会有思路!