鏈表的反轉(遞歸和非遞歸)

鏈表的反轉(遞歸和非遞歸兩種)

鏈表的反轉
示例
輸入:1->2->3->4->5
輸出:5->4->3->2->1

  1. 遞歸
struct ListNode {
 int val;
 ListNode *next;
 ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
 ListNode* reverseList(ListNode* head) {
  if (head == NULL|| head->next == NULL)
  {
   return head;
  }
  ListNode * newHead = reverseList(head->next);
  head->next->next = head;
  head->next = NULL;
  return newHead;
 }
};
  1. 非遞歸
struct ListNode {
 int val;
 ListNode *next;
 ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
 ListNode* reverseList2(ListNode* head) {
  if (head == NULL || head->next == NULL)
  {
   return head;
  }
  ListNode * newHead = NULL;
  while (head != NULL)
  {
   ListNode * tmp = head->next;
   head->next = newHead;
   newHead->next = head;
   head = tmp;
  }
  return newHead;
 }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章