劍指Offer 15 反轉鍊錶

2021-08-08 12:07:01 字數 654 閱讀 5671

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。

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

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

# 返回listnode

def reverselist(self, phead):

# write code here

if phead == none or phead.next == none:

return phead

p_head = listnode(0)

while phead:

pnext = phead

phead = phead.next

pnext.next = p_head.next

p_head.next = pnext

return p_head.next

本題的實現中使用了乙個頭節點p_head,每次將phead(剩餘鍊錶中的第乙個節點)插入頭結點後面。最終phead指向空時返回p_head的下乙個節點即可返回翻轉的鍊錶。

劍指offer 15 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。反轉鍊錶只需改變鏈結方向,改變方向時需要將原本指向後乙個結點的鏈結方向指向前乙個結點,因此需要記錄下三個結點。include using namespace std struct listnode class solution listnode fron...

劍指offer 15 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。include using namespace std struct listnode class solution class solution1 return pfront1 else pnode next new listnode num int ...

劍指Offer(15) 反轉鍊錶

輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。使用三個指標,分別指向當前遍歷到的結點pnode 它的前乙個結點ppre以及後乙個結點pnext。在遍歷的時候,做結點的替換。例如 當前結點pnode 1,ppre 0,pnext 2,替換pnode.next ppre 同時向後遍歷,ppre pnode...