关于
lintcode系列,第35题,题目网址:https://www.lintcode.com/problem/reverse-linked-list/description
描述
翻转一个链表。
样例:
样例1:
对于链表 1->2->3, 翻转链表为 3->2->1
样例2:
对于链表 1->2->3->4, 翻转链表为 4->3->2->1
思路
头插法。
C++实现
/**
* Definition of singly-linked-list:
*
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: n
* @return: The new head of reversed linked list.
*/
ListNode * reverse(ListNode * head) {
// write your code here
if(head==NULL) {
return NULL;
}
ListNode *p=head->next;
ListNode *p1=head->next;
int i=1;
while(p!=NULL) {
p = p->next;
p1->next = head;
if(i==1) {
head->next=NULL;
}
i++;
head = p1;
p1 = p;
}
return head;
}
};