反向链表

在这里插入图片描述
C++

/**
 * 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) {
        stack<int> st;
        ListNode* p = head;
        
        while(p){
            st.push(p->val);
            p = p->next;
        }
        //这并不是尾插法,但是我认为是一种流氓的解法,不要在意他
        //这里进栈的元素是数值,千万别让节点(包括指针)一起弄,那样很难弄
        p = head;
        while(!st.empty()){
            p->val = st.top();
            st.pop();
            p = p->next;
        }
        return head;
    }
};

这里主流做法是头插法,原因是:
头插法完成后的顺序正好是原来顺序表的顺序的相反
尾插法的顺序正好和上面头插法的顺序相反

最后写一个头插法:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        new_head = None
        while head:
            temp = head.next # 保存head.next的指针
            head.next = new_head #这是将原来链表中的节点指向后面的指针指空
            new_head = head
            head = temp
        return new_head
            
发布了111 篇原创文章 · 获赞 32 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42738495/article/details/101644706