Merge pull request #266 from betNevS/master

更新 0019.删除链表的倒数第N个节点 go版本
This commit is contained in:
Carl Sun
2021-05-27 15:35:19 +08:00
committed by GitHub
2 changed files with 31 additions and 14 deletions

View File

@ -114,24 +114,28 @@ class Solution {
```
Go:
```Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
result:=&ListNode{}
result.Next=head
var pre *ListNode
cur:=result
i:=1
for head!=nil{
if i>=n{
pre=cur
cur=cur.Next
dummyHead := &ListNode{}
dummyHead.Next = head
cur := head
prev := dummyHead
i := 1
for cur != nil {
cur = cur.Next
if i > n {
prev = prev.Next
}
head=head.Next
i++
}
pre.Next=pre.Next.Next
return result.Next
prev.Next = prev.Next.Next
return dummyHead.Next
}
```

View File

@ -153,6 +153,19 @@ func swapPairs(head *ListNode) *ListNode {
}
```
```go
// 递归版本
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
next := head.Next
head.Next = swapPairs(next.Next)
next.Next = head
return next
}
```
Javascript:
```javascript
var swapPairs = function (head) {