【基础操作】链表反转

Posted on 2018-01-27 15:42  Unkn0wnnnnn  阅读(128)  评论(0)    收藏  举报

链表反转的方法有很多,自己的思路可以大致归为亮点,第一种是采用头插法从头到尾进行操作,这样的方法采用的是一种非递归的方式。具体源码如下:

 1 struct ListNode {
 2 
 3     int val;
 4 
 5     ListNode *next;
 6 
 7     ListNode(int x) : val(x), next(NULL) {}
 8 }
 9 class Solution{
10 public:
11     ListNode* ReverseLinkNode(ListNode* head){
12         if(head->next==NULL||head==NULL)
13             return head;
14         ListNode* newHead=NULL;
15         ListNode* pHead=head;
16         while(pHead!=NULL){
17             ListNode* temp=pHead->next;
18             pHead->next=newHead;
19             newHead=pHead;
20             pHead=temp;
21         }
22         return newHead;
23     }
24 };

与此同时相对于头插法这样的非递归方式实现的方法,可以考虑采用从尾部进行操作的方式,这样可以使用一种递归的方式来实现,具体源码如下:

class Solution{
public:
    ListNode* ReverseListNode(Listnode* head){
        if (head==NULL||head->next==NULL)
            return head;
        ListNode* newHead=ReverseListNode(head->next);
        head->next->next=head;
        head->next=NULL;
        return newHead;
    }
};