反转一个链表

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路:首先此链表没有头节点,只有下一个节点,所以我们在分析的时候要想方法通过下一个节点的指向来达到反转效果,

迭代方法:

 //伪代码:
 /**
  * Definition for singly-linked list.
  * struct ListNode {
  *     int val;
  *     ListNode *next;
  *     ListNode(int x) : val(x), next(NULL) {}
  * };
  */
 class Solution {
 public:
     ListNode* reverseList(ListNode* head) {
         while(head==NULL||head->next==NULL)
              return head;
         ListNode* p=NULL;
         while(head){
         ListNode* temp=head->next;
         head->next=p;
         p=head;
         head=temp;
         }
              return p;       
     }
 };

递归方法:

//伪代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        while(head==NULL||head->next==NULL)
            return head;
        ListNode* newnode =reverseList(head->next);
        head->next->next=head;
        head->next=NULL;
        return newnode;
    }
};

学习常言:户枢不蠹,流水不腐