zoukankan      html  css  js  c++  java
  • 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("
    ");
    }
    
    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);
    }
  • 相关阅读:
    如何在Altium中下载并添加软件没有的苦文件【转】
    20121124
    变量作用域&函数作用域
    http相关知识
    函数声明和函数表达式
    js中constructor和prototype
    委托模式
    js跨域
    原型和原型链
    javascript 数据类型
  • 原文地址:https://www.cnblogs.com/chrischeng/p/4807681.html
Copyright © 2011-2022 走看看