您的位置:首页 > 其它

leetcode206 Reverse Linked List(反转链表)

2018-10-25 17:11 651 查看
版权声明:个人博客网址 https://29dch.github.io/ GitHub网址 https://github.com/29DCH,欢迎大家前来交流探讨和fork! https://blog.csdn.net/CowBoySoBusy/article/details/83382829

题目链接
https://leetcode.com/problems/reverse-linked-list/
知识点:
考察链表指针相关知识
思路:
用pre、cur、next三个指针操作。反转完毕后返回此时的头结点指针pre即可
代码:

/**
* 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* pre = NULL;
ListNode* cur = head;
while(cur != NULL)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};

AC代码加测试如下:

#include <bits/stdc++.h>
using namespace std;

struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

ListNode* createLinkedList(int arr[], int n)
{
if(n == 0)
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for(int i=1; i<n; i++)
{
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}

void printLinkedList(ListNode* head)
{
ListNode* curNode = head;
while(curNode!=NULL)
{
cout<<curNode->val<<" -> ";
curNode = curNode->next;
}
cout<<"NULL"<<endl;
}

void deleteLinkedList(ListNode* head)
{
ListNode* curNode = head;
while(curNode!=NULL)
{
ListNode* delNode = curNode;
curNode = curNode->next;
delete delNode;
}
}

class Solution
{
public:
ListNode* reverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* cur = head;
while(cur != NULL)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};

int main()
{
int arr[]= {1,2,3,4,5};
int n = sizeof(arr)/sizeof(int);
ListNode* head = createLinkedList(arr,n);
printLinkedList(head);
ListNode* head1 = Solution().reverseList(head);
printLinkedList(head1);
deleteLinkedList(head1);
return 0;
}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: