前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang刷leetcode 链表(3)反转链表

golang刷leetcode 链表(3)反转链表

作者头像
golangLeetcode
发布2022-08-02 15:56:22
2310
发布2022-08-02 15:56:22
举报
文章被收录于专栏:golang算法架构leetcode技术php

反转从位置 mn 的链表。请使用一趟扫描完成反转。

说明: 1 ≤ mn ≤ 链表长度。

示例:

代码语言:javascript
复制
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

解题思路:

找到起始位置,记录开始旋转之前的位置和之后的位置,旋转中间元素,注意边界

代码语言:javascript
复制
/**
 * 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 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

代码语言:javascript
复制
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
代码语言:javascript
复制
/**
 * 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
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-03-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 golang算法架构leetcode技术php 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 分隔链表
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档