问题描述
实现一个单链表的翻转。例如给定链表如下:
1->2->3->4
翻转后,结果为:
4->3->2->1
实现方式
//翻转指针
//实现思路:本人第一思路如此(比较笨拙)
//三指针,分情况讨论的(流汗,估计面试的话,一轮游的水平)。
int reverse(struct node** node){
struct node* tmp = (*node)->next;
struct node* last = NULL;
struct node* pre = tmp;
if(tmp->next){
tmp = tmp->next;
}
if(tmp->next->next){
last = tmp->next;
}
if(tmp==NULL){
*node = pre;
return 0;
}
if(last==NULL){
tmp->next = pre;
pre->next = NULL;
*node = tmp;
return 0;
}
pre->next = NULL;
//直接移动即可
while (last) {
tmp->next = pre;
pre = tmp;
tmp = last;
last = last->next;
}
if(tmp!=NULL){
tmp->next = pre;
}
(*node)->next = tmp;
return 0;
}
实现方式二:
翻转的本质:就是记录下一个元素的指针,将当前元素指向上一个元素即可
int reverse2(struct node** node){
struct node* head = *node;
if(head == NULL){
return 0;
}
//记录上一个元素
struct node* pre = NULL;
//记录当前一个元素
struct node* p = head->next;
struct node* h =NULL;
while (p) {
h = p;
struct node* tmp = p->next;
p->next = pre;
pre = p;
p = tmp;
}
return 0;
}
另外附上C语言实现链表、打印链表的工具类
#include <stdio.h>
//声明链表结点
struct node{
int value;
struct node * next;
};
extern int make(struct node** node,int* org,int len);
//构造一个链表
int make(struct node** node,int* org,int len){
if(len<=0){
return -1;
}
//构造头结点(并且从第二个结点开始放数据)
*node = (struct node*)malloc(sizeof(struct node));
struct node* tmp = *node;
int i = 0;
while (i<len) {
tmp->next = (struct node*)malloc(sizeof(struct node));
tmp->next->value = org[i];
tmp->next->next = NULL;
tmp = tmp->next;
i++;
}
return 0;
}
//打印一个链表
void print(struct node* node){
struct node* tmp = node->next;
while (tmp) {
printf(" %d ", tmp->value);
tmp = tmp->next;
}
printf("\n");
}