Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reverse Linked List #17

Open
walterzhu29 opened this issue Jun 25, 2017 · 0 comments
Open

Reverse Linked List #17

walterzhu29 opened this issue Jun 25, 2017 · 0 comments

Comments

@walterzhu29
Copy link
Owner

Description:

Reverse a linked list.

Example:

For linked list 1->2->3, the reversed linked list is 3->2->1

Link:

http://www.lintcode.com/en/problem/reverse-linked-list/

解题思路:

针对每个节点curr,只要改变该节点的next,让其指向curr前一个节点(需要用一个变量prev储存),然后再对这个节点的下个节点进行相同的操作。
这道题搞清楚以后,针对k-group那道题的反转代码就会写了。

Tips:

在进行反转操作之后,head已经不是第一个节点了而是最后一个,此时用dummy并不好用,反而直接返回prev这个点方便。

Time Complexity:

O(n),n为节点个数

完整代码:

ListNode *reverse(ListNode *head) 
    {
        ListNode *temp; 
        ListNode *curr = head; 
        ListNode *prev = NULL;
        while(curr != NULL)
        {
            temp = curr->next;
            curr->next = prev;
            prev = curr;
            curr = temp;
        }
        return prev;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant