C Python 鍊錶逆序 反轉鍊錶

2021-10-03 05:23:00 字數 2092 閱讀 1524

**

已知煉表頭節點指標head,將鍊錶逆序。(不可申請額外空間)

#include

struct listnode

//建構函式};

class

solution

~solution()

listnode*

reverselist

(listnode* head)

return new_head;

//返回新煉表頭節點

//method-2 recursive solution, time:o(n) and space: o(n)

/* if (head == nullptr || head->next == nullptr)

listnode* p = reverselist(head->next);

head->next->next = head;

head->next = nullptr;

return p;*/}

};intmain()

head = solve.

reverselist

(&a)

;printf

("after reverse:\n");

while

(head)

return0;

}

執行結果

before reverse:12

345after reverse:54

321**輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭

# -*-coding:utf-8-*-

class

listnode

:def

__init__

(self, x)

: self.val = x

self.

next

=none

class

solution

:def

reverselist

(self, phead)

:if phead ==

none

:return

none

if phead.

next

==none

:return phead

leftpointer = phead

midpointer = phead.

next

rightpointer = phead.

next

.next

leftpointer.

next

=none

while rightpointer !=

none

: midpointer.

next

= leftpointer

leftpointer = midpointer

midpointer = rightpointer

rightpointer = rightpointer.

next

midpointer.

next

= leftpointer

return midpointer

if __name__ ==

'__main__'

: l1 = listnode(1)

l2 = listnode(2)

l3 = listnode(3)

l4 = listnode(4)

l5 = listnode(5)

l1.next

= l2

l2.next

= l3

l3.next

= l4

l4.next

= l5

s = solution(

) r1=s.reverselist(l1)

while r1:

print

(r1.val)

r1=r1.

next

執行結果為:

543

21

鍊錶 反轉鍊錶

問題 兩兩交換鍊錶中的節點 問題 k 個一組翻轉鍊錶 問題鏈結 利用棧先進後出的特性,遍歷鍊錶,將每個結點加入棧中,最後進行出棧操作,先出棧的結點指向臨近的後出棧的結點。definition for singly linked list.struct listnode class solution ...

(鍊錶構建)鍊錶逆序

一直煉表頭結點指標head,將鍊錶逆序。不可申請額外空間 include using namespace std struct listnode int main 實際最終執行的 include using namespace std struct listnode 這個建構函式有點沒看懂,是一種什...

鍊錶 鍊錶反轉I

package com.hnust.reversal public class listnode public listnode int value,listnode next override public string tostring 我們可以通過把鍊錶中鏈結節點的指標反轉過來,從而改變鍊錶的...