LeetCode 206 单链表翻转
https://leetcode.com/problems/reverse-linked-list/
思路很简单,分别设置三个结点,之后依次调整结点1和结点2的指向关系。
Before: pre -> nxt -> nxtnxt -> ..... Here current = pre,nxt = pre->next, nxtnxt = nxt->next.
After: pre <- nxt nxtnxt -> ..... Here current = nxt, nxt = nxtnxt
代码如下(附加了一个简单的初始化链表的实例,VS2012下测试PASS)
#include "stdio.h" #include "stdlib.h" #include "string.h" #include <ctype.h> struct ListNode { int val; struct ListNode *next; }; struct ListNode* initListNode(void){ struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)); head->val = 1; head->next = NULL; } void pushNode(struct ListNode* head, int val){ struct ListNode* tmp; struct ListNode* pre = head; while (pre->next != NULL) pre = pre->next; tmp = (struct ListNode*)malloc(sizeof(struct ListNode)); pre->next = tmp; tmp->val = val; tmp->next = NULL; } void printListNode(struct ListNode* head){ struct ListNode* pre = head; while (pre != NULL){ printf("%-4d", pre->val); pre = pre->next; } printf("\n"); } struct ListNode* reverseList(struct ListNode* head) { struct ListNode* current; struct ListNode* nxt; struct ListNode* nxtnxt; if (head == NULL) return head; else if (head->next == NULL) return head; else{ current = head; nxt = current->next; while (nxt != NULL){ nxtnxt = nxt->next; nxt->next = current; current = nxt; nxt = nxtnxt; } head->next = NULL; return current; } } int main(){ int i; struct ListNode* head = initListNode(); for (i = 2; i < 10; i++){ pushNode(head,i); } printListNode(head); head = reverseList(head); printListNode(head); }