以下是Leetcode上一些关于链表的基本题目:
Leetcode#206:反转链表
题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
算法思路
倒转=将结点依次头插到另一个链表中
代码实现
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* p = NULL;
while( head != NULL){
swap(p, head->next);
swap(head, p);
}
return p;
}
};
执行用时:4ms , 内存消耗:10.2MB
/**
* 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 = NULL;
while( head ){
ListNode* t = p;
p = head;
head = head->next;
p->next = t;
}
return p;
}
};
执行用时:12ms , 内存消耗:10.2MB