反转链表

85 阅读1分钟

反转链表思路:

  1. 通过遍历原链表,取出原链表node,不断插入到新链表的头节点。
  2. 递归实现。

代码实现:

C/C++:
typedef struct ListNode {
int val;
struct ListNode *next; } ListNode;

class Solution {
public:

方式1思路实现:

ListNode *reverseList(ListNode *head) {

  ListNode new_head, *p = head, *q;  
  new_head->next = nullptr;
  while(p)  {  
    q = p->next;  
    p->next = new_head.next;  
    new_head.next = p;  
    p = q;
  } 
  return new_head.next;
  }    

}

方式2思路实现:

ListNode *reverseList(ListNode *head) {

  if (head == nullptr || head->next == nullptr){ 
    return head;
  }  
  ListNode *tail = head->next;
  ListNode *new_head = reverseList(head->next);
  head->next = tail->next;
  tail->next = head;
  return new_head;

}