反转单链表检验我们是否能够真正灵活使用它,也是面试频频被问道的一个题目。
例如反转上面单链表的方法之一:
黑色结点的下一个结点现在是空。因此,我们停止这一过程并返回新的头结点 15。
根据以上提示,请补全下面代码:
/**
* 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) {
ListNode* pre =NULL;
ListNode* cur = head;
ListNode* temp =NULL;
while (cur!=NULL){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
python3
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
class Solution():
def reverselist(self,head):
pre =None
cur =head
while cur:
temp =cur.next # 存储下一个结点的值
cur.next = pre # 将当前指向下一个结点的值放空
pre = cur # 将当前的值给到pre
cur = temp
return pre
if __name__ == '__main__':
lists = [2,3,4,5,6,7,8,9]
head = ListNode(None)
temp = head
for item in lists:
newnode = ListNode(item)
temp.next = newnode
temp = newnode
head = head.next
result =Solution()
res = result.reverselist(head)
while res:
print(res.val)
res = res.next