LeetCode (34) Reverse Linked List

题目描述

Reverse a singly linked list.

例如: 1 -> 2 -> 3 -> 4 -> 5 -> 6 ==> 6 -> 5 -> 4 -> 3 -> 2 -> 1

本题比较简单,使用两个指针,,一个指针(p)表示前一个结点,另一个(l)表示当前结点。主要指针操作如下:

ListNode* t = l -> next; // next of current nodel -> next = p;// reverse node lp = l;// move to next nodel = t;

完整代码为:

/** * 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) {if (!head)return NULL;ListNode* p = head;ListNode* l = head->next;p->next = NULL;while(l){ListNode* t = l->next;l->next = p;p = l;l = t;}return p;}};

每个人的生命都是可以绽放美丽,只要你珍惜。

LeetCode (34) Reverse Linked List

相关文章:

你感兴趣的文章:

标签云: