Reverse Linked List[LeetCode]

来源:互联网 发布:华为v8连上数据不能上 编辑:程序博客网 时间:2024/05/10 12:07

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

题目要求:反转单链表

通过在反转过程中保存临时节点的方式对链表进行反转

遇到问题主要有:在节点建立后需要进行节点的内存分配申请,在C语言当中采用malloc的方式

如:新建一个结构体节点 ListNode* node; node = (ListNode*)malloc(sizeof(ListNode));

在c++当中可通过new的方式去申请内存分配,如ListNode* node = new ListNode;

c++代码:

#include<cstdio>#include<cstring>#include<string>#include<cstdlib>#include<map>#include<iostream>using namespace std;struct ListNode {int val;    ListNode *next;};class Solution {public:    ListNode* reverseList(ListNode* head) {if(head == NULL || head->next == NULL){return head;}ListNode* pre = head;ListNode* next = head->next;    ListNode* nextNext = head->next->next;    pre->next = NULL; while(next){nextNext = next->next;next->next = pre;pre = next;next = nextNext;}return pre;}};ListNode* createListNode(){ListNode* node1 = new ListNode;node1->val = 1;ListNode* node2 = new ListNode;node2->val = 2;node1->next = node2;ListNode* node3 = new ListNode;node3->val = 3;node2->next = node3;node3->next = NULL;return node1;}int main(){ListNode* head = new ListNode;ListNode* node = new ListNode;head = createListNode();node = head;while(node){cout << node->val << " ";node = node->next;}cout << endl;Solution s;node = s.reverseList(head);while(node){cout << node->val << " ";node = node->next;}cout << endl;}


0 0
原创粉丝点击