LeetCode—206リバースリンクリストCpp&Python

LeetCode—206リバースリンクリストCpp&Python

質問の要件:リンクリストヘッドのポインターを渡し、リンクリストを逆にします

プロセスは次のとおりです。
入力:1-> 2-> 3-> 4-> 5-> NULL
出力:5-> 4-> 3-> 2-> 1-> NULL

1.方法とアイデア

方法1:反復法
リンクリストをたどるプロセスで、現在のノードが前のノードを指すようにします。さらに、次のノードを格納し、最終的に新しいヘッドノードに戻るには、別のポインターが必要です。
プロセスは次のとおりです

ここに画像の説明を挿入
トラバースする場合、3つのステップを完了します。
ステップ1:
現在のノードが前のノードを指すnew_headステップ
2:
新しいヘッドがヘッドの位置に移動しますステップ3

ヘッドが次の位置に移動します。このプロセスでは、次のノードを導入して位置情報を保存し、操作を完了する必要があります。


方法2:再帰再帰
のアイデアは、最初に最後まで再帰し、最後のノードを見つけ、最後のノードから開始して矢印の方向を変えることです。
マークアップテキスト
再帰的な終了条件:

if(head == NULL || head->next == NULL) 
    return head;

ここに画像の説明を挿入

最後のノードを取得した後、再帰の上位層に戻ります。pは元のリンクリストの最後のノードを指し、これがヘッドノードである必要があります。後続のpを変更する必要はなく、再帰の上位層に戻り続けます。

ヘッドの次のポイントをそれ自体を指すように変更し、次に新しいリンクリストの最後のノードとして、ヘッドの次を空にポイントします

head->next->next = head;
head->next = NULL;

ここに画像の説明を挿入
再帰は終了し、最終的な戻り値はp(ヘッドノード)です。
ここに画像の説明を挿入

2、C ++コード

#include <stdio.h>

struct ListNode {
    
    
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {
    
    }
};

class Solution {
    
    
public:
	ListNode* ReverseTheList1(ListNode* head){
    
    //迭代法
		ListNode *new_head = NULL;
		while (head)  //进行遍历
		{
    
    
			ListNode *next = head->next;
			head->next = new_head;
			new_head = head;
			head = next;
		}
		return new_head;
	}
	ListNode* ReverseTheList2(ListNode* head) {
    
    //递归法
		if (head == NULL || head->next == NULL)
			return head;

		ListNode* p = ReverseTheList2(head->next);
		head->next->next = head;
		head->next = NULL;
		return p;
	}
	
};
	int main() {
    
    //测试用例
		ListNode a1(1);ListNode b1(2);ListNode c1(3);ListNode d1(4);ListNode e1(5);
		a1.next = &b1; b1.next = &c1; c1.next = &d1; d1.next = &e1;
		ListNode a2(1); ListNode b2(2); ListNode c2(3); ListNode d2(4); ListNode e2(5);
		a2.next = &b2; b2.next = &c2; c2.next = &d2; d2.next = &e2;
		Solution solve;
		ListNode *head1 = solve.ReverseTheList1(&a1);
		ListNode *head2 = solve.ReverseTheList2(&a2);
		while (head1){
    
    
			printf("%d\n", head1->val);
			head1 = head1->next;
		}
		printf("------------\n");
		while (head2) {
    
    
			printf("%d\n", head2->val);
			head2 = head2->next;
		}
		return 0;
	}
	//Time:O(n) Sapce:O(1)

3、Pythonコード

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

class Solution:
	#迭代法
    def reverseList1(self, head: ListNode) -> ListNode:
        pre, cur = None, head
        while cur:
            temp = cur.next
            cur.next = pre
            pre, cur = cur, temp
        return pre

	#递归法
     def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        newhead = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return newhead

おすすめ

転載: blog.csdn.net/weixin_45680994/article/details/108531231