码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-206 Reverse Linked List

时间:2018-10-28 21:55:16      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:def   lin   output   list   struct   tput   sel   eve   另一个   

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
想法:设置两个指针,一个指向当前节点,另一个指向当前节点的写一个节点。然后逐个反转
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {

    if(head==NULL){
        return head;
    }
    struct ListNode *p=head->next;//p指针指向要被反转的链表
    head->next=NULL;//让head指向空
    while(p!=NULL){
        struct ListNode *tmp=p->next;//ptmp指向p的下一个节点
        p->next=head;//将p指向head
        head=p;//反转完毕,head移动到p的位置
        p=tmp;//p移动到tmp的位置   
    }
    return head;

}

leetcode-206 Reverse Linked List

标签:def   lin   output   list   struct   tput   sel   eve   另一个   

原文地址:https://www.cnblogs.com/tingweichen/p/9866982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!