反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明: 1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
解题思路:
找到起始位置,记录开始旋转之前的位置和之后的位置,旋转中间元素,注意边界
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseBetween(head *ListNode, m int, n int) *ListNode {
if head==nil || head.Next==nil{
return head
}
he:=&ListNode{}
he.Next=head
cur:=he
for i:=0;i<m-1;i++{
cur=cur.Next
}
h:=cur.Next
t:=h.Next
var tail *ListNode
for j:=0;j<n-m;j++{
temp:=t.Next
t.Next=h
if tail==nil{
tail=h
}
h=t
t=temp
}
cur.Next=h
if tail!=nil{
tail.Next=t
}
return he.Next
}
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func partition(head *ListNode, x int) *ListNode {
if head==nil{
return nil
}
var h1,t1,h2,t2 *ListNode
for head!=nil {
if head.Val<x{
if h1==nil{
h1=head
t1=head
}else{
t1.Next=head
t1=t1.Next
}
}else{
if h2==nil{
h2=head
t2=head
}else{
t2.Next=head
t2=t2.Next
}
}
head=head.Next
}
if t1!=nil{
t1.Next=h2
}else{
return h2
}
if t2!=nil{
t2.Next=nil
}
return h1
}
本文分享自 golang算法架构leetcode技术php 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!