# 链表
翻转链表方法
#include <iostream>
#include <algorithm>
using namespace std;
struct List{
List *next;
int val;
};
void Creat(List* head,int n){
List *p=head;
for(int i=1;i<=n;i++){
List *tmp=new List;
tmp->val=i;
tmp->next= nullptr;
p->next=tmp;
p=p->next;
}
}
void traver(List* head){
List* tmp=head->next;
while (tmp!= nullptr){
cout<<tmp->val<<" ";
tmp=tmp->next;
}
cout<<endl;
}
List* test(List* head,int k){
List* end=head->next;
while(end->next!= nullptr){
end=end->next;
}
end->next=head->next; //把链表变成环,尾节点接到头节点
List *tmp=end->next;
//循环到需要更改到节点前一个
for(int i=0;i<k-1;i++){
tmp=tmp->next;
}
//把下一个节点作为头节点,并赋值
List *ans=new List;
ans->next=tmp->next;
//把下一个节点的next指针改为null
tmp->next= nullptr;
return ans;
}
int main() {
List *head=new List;
Creat(head,5);
traver(test(head,3));
}
package main | |
import "fmt" | |
type ListNode struct { | |
Next *ListNode | |
Val int | |
} | |
func InitList(head *ListNode, n int) { | |
tmp := head | |
for i := 1; i <= n; i++ { | |
res := new(ListNode) | |
res.Val = i | |
res.Next = nil | |
tmp.Next = res | |
tmp = tmp.Next | |
} | |
} | |
func Show(head *ListNode) { | |
tmp := head.Next | |
for tmp != nil { | |
fmt.Println(tmp.Val) | |
tmp = tmp.Next | |
} | |
} | |
func Reversal(head *ListNode, k int) *ListNode { | |
tmp := head.Next | |
for tmp.Next != nil { | |
tmp = tmp.Next | |
} | |
tmp.Next = head.Next | |
res := tmp.Next | |
for i := 0; i < k-1; i++ { | |
res = res.Next | |
} | |
ans := new(ListNode) | |
ans.Next = res.Next | |
res.Next = nil | |
return ans | |
} | |
func main() { | |
head := new(ListNode) | |
InitList(head, 5) | |
Show(Reversal(head, 3)) | |
} |