Reverse Linked List II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Reverse Linked List II相关的知识,希望对你有一定的参考价值。
描述
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example: Given 1->2->3->4->5->nullptr, m = 2 and n = 4,
return 1->4->3->2->5->nullptr.
Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
这是第一次实现的代码(很挫—_—)
typedef struct ListNode { int _var; struct ListNode *_next; ListNode(int var) :_var(var) , _next(NULL) {} }node,*node_p; class Solution { public: node_p ReserveList(node_p &head,int m,int n) { //检查边界条件 if (head == NULL){ printf("List is NULL\n"); return NULL; } if (m<1||n<m){//未检查n的边界 printf("rangle is error\n"); return NULL; } if (n == m) return head; //****************** node_p prev = head; node_p a = head; node_p b = head; for (int i = 2; i < m; ++i){ prev = prev->_next; } for (int i = 1; i < m; ++i){ a = a->_next; } for (int i = 1; i < n; ++i){ b = b->_next; } node_p tmp = new node(-1); //a->_next = b->_next; node_p last = a; while (a != b){ if (m == 1) prev = prev->_next; else prev->_next = a->_next; a->_next = tmp->_next; tmp->_next = a; if (m == 1) a = prev; else a = prev->_next; } if (m == 1){ prev = b->_next; b->_next = tmp->_next; tmp->_next = b; last->_next = prev; node_p Newhead = tmp->_next; free(tmp); return Newhead; } prev->_next = b->_next; b->_next = tmp->_next; tmp->_next = b; last->_next = prev->_next; prev->_next = tmp->_next; free(tmp); return head; } };
这是重新写的代码(还是很挫,感觉整个人都不好了)
reverse_linklist.h:
#pragma once #include <iostream> #include <assert.h> #include <stdlib.h> using namespace std; typedef struct ListNode { int _var; ListNode *_next; ListNode(int var) :_var(var) ,_next(NULL) {} }node,*node_p; class Solution { public: node_p reverse_link(node_p &list,int m,int n) { //边界检查 if(list==NULL) return NULL; if(m<1||m>n){ cout<<"parameter error"<<endl; return NULL; } if(m==n) return list; node dummy(-1); node_p head=&dummy; head->_next=list; for(int i=0;i<m-1;++i){ head=head->_next; } node_p first=list; for(int i=1;i<m;++i) first=first->_next; node_p second=first; for(int i=m;i<n;++i) second=second->_next; node_p tmp=first; //核心步骤 while(tmp!=second){ tmp=first->_next; first->_next=tmp->_next; tmp->_next=head->_next; head->_next=tmp; } if(m==1) return head->_next; return list; } };
test.cpp
#include "reverse_linklist.h" using namespace std; int main() { node_p n1 = new node(1); node_p n2 = new node(2); node_p n3 = new node(3); node_p n4 = new node(4); node_p n5 = new node(5); n1->_next = n2; n2->_next = n3; n3->_next = n4; n4->_next = n5; Solution s; node_p newhead=s.reverse_link(n1,3,5); while (newhead != NULL){ node_p tmp = newhead; cout<<tmp->_var<<" "; newhead = newhead->_next; free(tmp); } cout<<endl; return 0; }
运行结果:
还是来看看人家的代码吧:
自己还是弱的很,需要更努力啦^_^
《完》
本文出自 “零蛋蛋” 博客,请务必保留此出处http://lingdandan.blog.51cto.com/10697032/1782776
以上是关于Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 92. Reverse Linked List II