Reverse Linked List
来源:互联网 发布:单片机程序员招聘 编辑:程序博客网 时间:2024/06/06 03:16
Reverse a singly linked list.
单链表的逆序有两种方法,一种是递归的,另一种是非递归的(头插法)。
递归解法如下,耗时11ms:
/** * 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) { if(head == NULL || head->next == NULL) return head; ListNode* p = reverseList(head->next); head->next->next = head; head->next = NULL; return p; }};
非递归解法如下,耗时8ms:
/** * 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) { if(head == NULL || head->next == NULL) return head; ListNode* p = head->next; head->next = NULL; ListNode* q; while(p) { q = p; p = p->next; q->next = head; head = q; } return head; }};
0 0
- Single linked list reverse
- reverse a linked list
- Reverse a linked list.
- Reverse a linked list
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- 当程序员老去
- 黑马-C语言-结构体
- Linux下的hosts文件
- 1006. Sign In and Sign Out (25)
- sql建自增序列号
- Reverse Linked List
- 【中文分词】亲手开发一款中文分词器--前言
- ROWNUM 与 ROW_NUMBER()OVER() 的区别
- C#使用Log4Net记录日志
- C#设计模式学习之【单例模式】
- HTML基础介绍二(图像和超级链接)
- ReactiveCocoa - iOS开发的新框架
- 台大机器学习基石笔记(二)——VC 维1
- ipv6 记录1