Reverse Linked List I&&II——数据结构课上的一道题(经典必做题)
2024-10-01 22:11:51
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 ≤ m ≤ n ≤ 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;
}
}
};
最新文章
- MongoDB的用户管理(6)
- AfxMessageBox和MessageBox区别
- LFI漏洞利用总结
- .net中ckeditor的应用
- 路由器WDS实际案例
- Python补充02 Python小技巧
- css3media响应式布局
- [Leetcode][Python]53: Maximum Subarray
- Delphi_MemoryModule — load DLL from memory. Also includes hooking utilities.
- mysql 本地操作
- reids数据类型
- 【动态规划】洛谷P1004方格取数
- Java基础学习笔记二十一 多线程
- Chart.js 與 ASP.NET MVC 整合應用
- 17 , CSS 区块、浮动、定位、溢出、滚动条
- phpcms公共函数库 总结
- Supervisor的作用与配置
- 接口测试工具之Postman笔记
- LeetCode算法题-Power Of Two(Java实现)
- JS之Fetch