Foreign perspectives


In this paper, the appearance of the sequence as an example, add some small means to achieve a similar single linked listdummyEffect, turn special into ordinary


It is very troublesome to deal with the boundary of the algorithm from the perspective of the domain, either missing conditions or writing a lot of similar processing logic, which is not very elegant.


The special boundary conditions are transformed into ordinary elements and smoothed directly.

Look-and-say sequence

  • Double pointeriFirst, but the last element cannot handle itself, so a string bit is added to the last bit$Reasonable cross-border repair
  • forAndfor rangeTwo worlds, one index byte, condition detection will determine the variability, and the latter loop copy, run value output

The example returns the nth appearance string value

import "bytes"
import "strconv"
func countAndSay( n int ) string {
    rs := "1"
    var buf bytes.Buffer
    for ;n>1;n--{
        rs +="$"
        for k,i:=0,1;i< len(rs);i++{
            if rs[i-1]!=rs[i]{
        rs = buf.String()
    return rs

Single linked list dummy

The element deletion of single linked list needs precursor element operation. The header node often needs special treatment because there is no precursor.
Use to construct dummy node, simplify the processing logic, and operate the head node as an ordinary node. In the example, delete the penultimate node

func removeNthFromEnd( head *ListNode ,  n int ) *ListNode {
    dummy := &ListNode{
        Next: head,
    slow,fast := dummy, dummy
    for fast != nil && fast.Next != nil{
        if n < 0 {
            slow = slow.Next
        fast = fast.Next
    slow.Next = slow.Next.Next
    return dummy.Next
  • The speed pointer finds the front node of the deleted node
  • Using sentinel virtual node to solve the original chain head operation bug

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]