Reverse Linked List

原创 2015年07月07日 17:46:05

解题思路:三指针,跟踪算法的过程如下:
算法跟踪

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *p;
        p = head;
        int counter = 0;
        for(; p != NULL; ) {
            counter++;
            p = p->next;
        }

        if(counter == 0) {
            return NULL;
        }

        if(counter == 1) {
            return head;    
        }

        if(counter == 2) {
            ListNode *p21, *p22;
            p21 = head;
            p22 = p21->next;
            p21->next = NULL;
            p22->next = p21;
            return p22;
        }

        ListNode *p1, *p2, *p3;
        p1 = head;
        p2 = head->next;
        p3 = head->next->next;
        head->next = NULL;
        for(; p3 != NULL; ) {
            p2->next = p1;
            p1 = p2;
            p2 = p3;
            p3 = p3->next;
        }
        p2->next = p1;
        return p2;




    }
};

相关文章推荐

链表基本概念和操作 及 206. Reverse Linked List

参考书目与链接: 1、基本概念,双向链表与循环链表 2、链表的创建,增加、删除节点,链表的逆序、排序和销毁等 3、链表基本操作(全) 4、双向、循环链表操作...
  • sqiu_11
  • sqiu_11
  • 2017年04月20日 10:59
  • 157

leecode - Reverse Linked List

链表逆序 不用申请内存 非递归方法 递归方法

( Leetcode 92 ) Reverse Linked List II

题目:Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one...

【Hackerrank】Reverse a doubly linked list

You’re given the pointer to the head node of a doubly linked list. Reverse the order of the nodes in...

LeetCode Reverse Linked List II

题目 Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Giv...

206. Reverse Linked List

Reverse a singly linked list. 逆置单链表。 Hint: 提示: A linked list can be reversed either iteratively ...

LeetCode 92. Reverse Linked List II

1. 题目描述 Reverse a linked list from position m to n. Do it in-place and in one-pass. For examp...

[LeetCode] Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1...
  • game115
  • game115
  • 2014年04月17日 23:29
  • 704

206. Reverse (Linked List)

题目:Reverse a singly linked list. Hint: A linked list can be reversed either iteratively or recursi...

LeetCode题解-206-Reverse Linked List Ⅰ

原题 迭代法 解题思路 新建两个ListNode变量p1与p2存放遍历时的节点与其后驱节点,原先为P1->P2,,遍历时将其反转P2-P1,遍历结束则整个链表翻转完毕。 需要注意的是h...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Reverse Linked List
举报原因:
原因补充:

(最多只允许输入30个字)