标签:null node ++ printf return nod main std sizeof
原创文章,拒绝转载
主要的思想是使用三个标记指针:preNode、curNode、nextNode,每次将curNode的next设为preNode,然后如果此时nextNode为空,跳出循环,将链表头指针的next设为NULL,返回链表尾指针;否则,preNode = curNode,curNode=nextNode,nextNode=nextNode -> next。
实现如下:
#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
int val;
struct Node *next;
} Node;
Node* reverse_list(Node *headNode) {
if (headNode == NULL) {
return NULL;
}
if (headNode -> next == NULL) {
return headNode;
}
if (headNode -> next -> next == NULL) {
Node* resNode = headNode -> next;
resNode -> next = headNode;
headNode -> next = NULL;
return resNode;
}
Node *preNode = headNode;
Node *curNode = preNode -> next;
Node *nextNode = curNode -> next;
for ( ; ; ) {
curNode -> next = preNode;
if (nextNode == NULL) {
break;
}
preNode = curNode;
curNode = nextNode;
nextNode = curNode -> next;
}
headNode -> next = NULL;
return curNode;
}
int main(int argc, char const *argv[])
{
int n;
int temp;
int i;
scanf("%d", &n);
if (n <= 0)
return 0;
Node* headNode = (Node*)malloc(sizeof(Node));
scanf("%d", &temp);
headNode -> val = temp;
headNode -> next = NULL;
Node *curNode = headNode;
for (i = 1; i < n; i++) {
scanf("%d", &temp);
curNode -> next = (Node*)malloc(sizeof(Node));
curNode -> next -> val = temp;
curNode -> next -> next = NULL;
curNode = curNode -> next;
}
curNode = reverse_list(headNode);
Node *tempNode;
while (curNode) {
tempNode = curNode;
curNode = curNode -> next;
printf("%d ", tempNode -> val);
free(tempNode);
}
printf("\n");
return 0;
}
标签:null node ++ printf return nod main std sizeof
原文地址:http://www.cnblogs.com/yanhewu/p/7857734.html