一.题目
二.解题思路
2.1 普通思路
反转箭头指向即可
cur设置为第一个元素1,pre为cur前的元素设置为None
- 先用temp保存下来cur的下一个元素
temp = cur.next
- 再将cur的箭头(
cur.next
)指向pre:cur.next = pre
- pre与cur都向后移
- 循环下去即可
2.2 递归思路
建议跟下文的代码结合看
第一次执行代码到ListNode newHead = reverseList(head.next);
进入到第二次recursive,执行到同样的位置又进入了第三次recursive,三次recursive对应图中的1,2,3.
第三次recursive继续往下执行代码head.next.next=head;head.next=null;
(图中4所示),此时head=3,head.next=null,箭头改变指向后结束第三次recursive,回到第二次recursive中(图中5所示)。
三.代码解析
3.1 普通方法
def reverseList(self, head: ListNode) -> ListNode:
pre = None #保存当前遍历的结点的前一个结点
cur = head #cur是当前遍历的结点
while cur: #开始便利,cur不为null为循环条件
temp = cur.next #temp保存cur.next
cur.next = pre #反转,cur指向pre
pre = cur #pre与cur都向后移
cur = temp
return pre #返回pre,即为新的头结点
3.2 递归方法
public ListNode reverseList(ListNode head) {
#/*如果传入的节点等于null则之间返回head说明只有一个,无需反转*/
#/*如果传入节点的下一个节点为null,说明递归结束,开始进行返回节点*/
if (head==null||head.next==null){
return head;
}
#/*进行递归循环,newHead保存的是最后一个节点的位置*/
ListNode newHead = reverseList(head.next);
head.next.next=head;
head.next=null;
return newHead;
}
3.3 总方法及输出
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# Function to initialize head
def __init__(self):
self.head = None
def reverseList(self, head: ListNode) -> ListNode:
pre = None #保存当前遍历的结点的前一个结点
cur = head #cur是当前遍历的结点
while cur: #开始便利,cur不为null为循环条件
temp = cur.next #temp保存cur.next
cur.next = pre #反转,cur指向pre
pre = cur #pre与cur都向后移
cur = temp
return pre #返回pre,即为新的头结点
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = ListNode(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.val)
temp = temp.next
llist = Solution()
llist.push(7)
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
print("Given linked list")
llist.printList()
llist.head = llist.reverseList(llist.head)
print("\nReversed Linked list")
llist.printList()
Output: