本文主要是介绍leetcode No206. Reverse Linked List(C++Python),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Question:
Reverse a singly linked list.
翻转链表
Algorithm:
2017/3/10之前写的都是写什么呀。。。。来更新一下解法
非递归:Assume that we have linked list 1 → 2 → 3 → Ø
, we would like to change it to Ø ← 1 ← 2 ← 3
.
重复以下过程
递归:
n1 → … → nk-1 → nk → nk+1 ← … ← nm
即:nk.next.next = nk;
Accepted Code:
非递归
C++:
class Solution {
public:ListNode* reverseList(ListNode* head) {ListNode* pre=NULL;ListNode* p=head;while(p!=NULL){ListNode* tmp=p->next;p->next=pre;pre=p;p=tmp;}return pre;}
};
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:def reverseList(self, head):pre = Nonecur = headwhile cur:tmp = cur.nextcur.next = prepre = curcur = tmpreturn pre
递归
class Solution {
public:ListNode* reverseList(ListNode* head) {if(head==NULL || head->next==NULL)return head;ListNode* p=reverseList(head->next);head->next->next=head;head->next=NULL;return p;}
};
这篇关于leetcode No206. Reverse Linked List(C++Python)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!