Reverse Linked List I

Question Solution

Reverse a singly linked list.

Reverse Linked List I

设置三个指针即可,非常简单:

/**
* 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* firstNode = head;
ListNode* preCurNode = head;
ListNode* curNode = head->next;//maybe null
while(curNode){
preCurNode->next = curNode->next;
curNode->next = firstNode;
firstNode=curNode;
curNode =preCurNode->next; }
return firstNode;
}
};

  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->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head==NULL||head->next==NULL||m==n)
return head;
ListNode* firstNode = head;
ListNode* preCurNode = head;
ListNode* curNode = head->next;//maybe null
ListNode* lastNode= head;
int flag=;
int m_flag=flag;
if(m==)
{
while(flag<n)
{
preCurNode->next = curNode->next;
curNode->next = firstNode;
firstNode=curNode;
curNode =preCurNode->next;
flag++;
}
return firstNode;
}
else
{
while(flag<n)
{
if(flag<m)
{
lastNode=firstNode;
firstNode=firstNode->next;
preCurNode =preCurNode->next;
curNode =curNode->next;
flag++;
}
else
{
preCurNode->next = curNode->next;
curNode->next = firstNode;
firstNode=curNode;
curNode =preCurNode->next;
lastNode->next=firstNode;
flag++;
} }
return head;
}
}
};

  

最新文章

  1. MongoDB的用户管理(6)
  2. AfxMessageBox和MessageBox区别
  3. LFI漏洞利用总结
  4. .net中ckeditor的应用
  5. 路由器WDS实际案例
  6. Python补充02 Python小技巧
  7. css3media响应式布局
  8. [Leetcode][Python]53: Maximum Subarray
  9. Delphi_MemoryModule — load DLL from memory. Also includes hooking utilities.
  10. mysql 本地操作
  11. reids数据类型
  12. 【动态规划】洛谷P1004方格取数
  13. Java基础学习笔记二十一 多线程
  14. Chart.js 與 ASP.NET MVC 整合應用
  15. 17 , CSS 区块、浮动、定位、溢出、滚动条
  16. phpcms公共函数库 总结
  17. Supervisor的作用与配置
  18. 接口测试工具之Postman笔记
  19. LeetCode算法题-Power Of Two(Java实现)
  20. JS之Fetch

热门文章

  1. 洛谷 [POI2007]BIU-Offices 解题报告
  2. 应用程序的日志通过rsyslog推送到syslog服务器
  3. C 位段,位域
  4. apue.3e 的安装 (基于ubuntu12.0.4)
  5. Endless Spin
  6. opencv2 直方图之calchist函数使用(转)
  7. 【计算机视觉】SIFT中LoG和DoG比较
  8. dalao&amp;话
  9. 还不会做! 树上的gcd 树分治 UOJ33
  10. PhotoSwipe 图片浏览插件使用方法