问题:
输入一个链表,从尾到头打印链表每个节点的值。
实现方式:
- 双向链表
- 单项链表通过交换元素进行反转链表(我的实现方式)
- 创建一个头结点,然后将链表复制到这个头结点这里
- 创建和链表相同长度的数组,将数组从末端进行赋值,模仿栈的方式进行实现。然后从头到尾打印数组得到反转列表的元素。
- 通过递归的方式打印链表的元素值。和栈的思想相同。
代码实现(C语言版)
对链表总体进行了一个小总结。
#include <stdio.h>
#include <stdlib.h>
typedef struct node *Link;
typedef struct node {
int data;
Link next;
} Node;
int len = 0;
Link initList() {
Link L = malloc(sizeof(Node));
L->next = 0;
return L;
}
int insert(Link L, int pos, int value) {
if (pos<0 || pos >len) {
return -1;
}
Link newNode = malloc(sizeof(Node));
newNode->data = value;
Link pointer = L->next;
if (pos == 0) {
L->next = newNode;
newNode->next = pointer;
++len;
}
else {
int i = pos;
while (--i) {
pointer = pointer->next;
}
if (pointer) {
newNode->next = pointer->next;
pointer->next = newNode;
++len;
}
}
return 0;
}
int delete(Link L, int pos) {
if (pos<0 || pos >=len) {
return -1;
}
Link pointer = L->next;
if (pos == 0) {
L->next = pointer->next;
free(pointer);
--len;
}
else {
int i = pos;
while (--i) {
pointer = pointer->next;
}
Link freeNode = pointer->next;
pointer->next = pointer->next->next;
free(freeNode);
--len;
}
return 0;
}
int find(Link L, int pos) {
if (pos<0 || pos>=len) {
return -1;
}
Link pointer = L->next;
int i = pos;
while (i--) {
pointer = pointer->next;
}
return pointer->data;
}
void print(Link L) {
Link pointer = L->next;
int i = len;
while (pointer) {
printf("%d ", pointer->data);
pointer = pointer->next;
}
printf("\n");
}
void reverse(Link L) {
Link endPointer = L->next;
while (endPointer->next) {
Link swaptPointer = endPointer->next;
endPointer->next = endPointer->next->next;
swaptPointer->next = L->next;
L->next = swaptPointer;
}
return;
}
int main(int argc, char *argv[]) {
Link L = initList();
int i, n, pos, value;
scanf("%d", &n);
for(i=0;i<n;++i) {
scanf("%d", &value);
insert(L, i, value);
}
reverse(L);
print(L);
}
网友评论