初级算法:翻转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路1:迭代:
思路很简单 使用三个指针 循环使后一个指向前一个 再用第三个指针保存没有翻转的剩余指针的位置
自己敲得程序运行不出结果

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* p=head->next;
        head->next=NULL;
        ListNode* q=p->next;
        ListNode* r;
        while(q){
            r=q->next;
            q->next=p;
            p=q;
            q=r;
        }
        head=q;
        return head;
    }
};

找到原因了,因为没有考虑周全,需要加一个是否为空的判断。

/**
 * 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) {
        if(head==NULL){
            return NULL;
        }
        ListNode* p=head;
        ListNode* q=head->next;
        head->next=NULL;
        while(q){
           ListNode* r=q->next;
            q->next=p;
            p=q;
            q=r;
        }
        head=p;
        return head;
    }
};

思路2:递归方法:运行不出来 不懂。
/**

  • 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) {
    if(head==NULL){
    return NULL;
    }
    if(head->next=NULL){
    return head;
    }
    ListNode* newHead=reverseList(head->next);
    head->next->next=head;
    head->next=NULL;
    return newHead;
    }
    };
发布了36 篇原创文章 · 获赞 0 · 访问量 620

猜你喜欢

转载自blog.csdn.net/weixin_43199933/article/details/102877233