Leetcode 206 Reverse Linked List
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目大意:反转单链表
提示:
反转一个链表可以用迭代或者递归的方法。你能都实现吗?
递归:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseList(ListNode* head) { 12 //最后一个节点会返回,作为头结点 13 if(head == NULL || head -> next == NULL) 14 return head; 15 //head->next 表示剩下的部分 16 ListNode* newHead = reverseList(head -> next); 17 head -> next -> next = head; 18 head -> next = NULL; 19 return newHead; 20 } 21 };
迭代:
越努力,越幸运