对于给定的单链表,我们如何将链表逆置,最理想的状态是原地逆转,接下来我们来分析一下算法,并给出Java和c两种解法,仅供参考!!!
分析算法
我们来看代码实现
C
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode {
int data;
struct Node* next;
}LNode;
LNode* InitList(LNode* L, int n) {
int i = 0;
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
LNode* tail = L;
while (i < n) {
LNode* newNode = (LNode*)malloc(sizeof(LNode));
int temp;
scanf("%d", &temp);
newNode->data = temp;
/*newNode->next = L->next;
L->next = newNode;*/
tail->next = newNode;
tail = newNode;
i++;
}
tail->next = NULL;
return L;
}
void print1(LNode* L) {
LNode* cur = L;
while (cur->next) {
cur = cur->next;
printf("%d ", cur->data);
}
}
void print2(LNode* L) {
LNode* cur = L;
while (cur->next) {
printf("%d ", cur->data);
cur = cur->next;
}
}
LNode* reverse(LNode* L) {
LNode* pre = NULL;
LNode* next = NULL;
while (L!=NULL) {
next = L->next;
L->next = pre;
pre = L;
L = next;
}
return pre;
}
int main() {
int n;
scanf("%d", &n);
LNode* L = (LNode*)malloc(sizeof(LNode));
L=InitList(L, n);
print1(L);
printf("\n");
L = reverse(L);
print2(L);
return 0;
}
Java
public class demo01 {
public static class Node{
public int value;
public Node next;
public Node(int data){
value=data;
}
}
public static Node reverseLinkedList(Node head){//逆序链表
Node next=null;
Node pre=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
public static void printList(Node head){
if(head==null)
return;
Node cur=head;
while(cur!=null){
System.out.print(cur.value+" ");
cur=cur.next;
}
}
public static void main(String[] args) {
Node n1=new Node(1);
n1.next=new Node(2);
n1.next.next=new Node(3);
n1=reverseLinkedList(n1);
printList(n1);
}
}
大家好好看看图解,如果觉得有用的话,不妨点个免费的关注哦,我们继续加油!