Skip to content

Commit b8af917

Browse files
authored
Update Readme.md
1 parent 40e830a commit b8af917

File tree

1 file changed

+7
-13
lines changed
  • Linked_List/092.Reverse-Linked-List-II

1 file changed

+7
-13
lines changed
Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,13 @@
11
### 092.Reverse-Linked-List-II
22

3-
#### 将一段链表逆序
4-
可以设置一个节点front==NULL,然后遍历中段节点的时候不断把节点加到front前面去,然后更新front保持位于新中段的队首。有多少元素就操作多少次。
5-
```cpp
6-
ListNode* front = NULL;
7-
for (int i=m; i<=n; i++)
8-
{
9-
ListNode* temp = p->next; // save the next node
10-
p->next=front;
11-
front=p;
12-
p=temp;
13-
}
14-
```
3+
本题比较考验对于链表操作的细节。
154

16-
另外要注意的是,在逆序操作前要保存中段的首元素的地址,因为逆序操作后该节点就成了中段的尾地址,需要靠它来链接后段链表
5+
我们先遍历到第m-1个和第m个节点。将第m-1个节点记为end_of_start,之后的next要重新指向逆序段的首节点
176

7+
从第m个节点到第n个节点,我们要做链表逆转的操作。基本的思想就是将向后指向的next,变更成向前指向。所以我们每操作一个cur,都要同时准确地知道prev和next。处理完之后,prev,cur,next都要正确地移动到下一个位置。最终处理完第n个节点后,此时的cur指向的是第n+1个节点,它就是第三段的首节点start_of_third,同时prev就是第二段的逆序的首节点。我们需要的操作是:
8+
```cpp
9+
end_of_first->next = start_of_third;
10+
start_of_second->next = start_of_third;
11+
```
1812

1913
[Leetcode Link](https://leetcode.com/problems/reverse-linked-list-ii)

0 commit comments

Comments
 (0)