题目要求:
翻转一个链表
样例
给出一个链表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: 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;
ListNode *head2 = new ListNode;
while(p != NULL){
ListNode *q = new ListNode;
q->val = p->val;
q->next = head2->next;
head2->next = q;
p = p->next;
}
return head2->next;
}
};