码迷,mamicode.com
首页 > 其他好文 > 详细

链表-常见题

时间:2018-09-04 23:32:41      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:str   fas   tmp   约瑟夫问题   return   效率   amp   pre   head   

struct  Node
{
    int _data;
    Node *_next;
};

逆序:

1)修改指向:效率较低

 1 Node* reverseList(Node *head) {
 2     if (head == 0) return head;
 3     Node *p = head->_next;
 4     if (p == 0) return head;
 5     Node *q = head, *tmp;
 6     while (p) {
 7         tmp = p->_next;
 8         p->_next = q;
 9         q = p;
10         p = tmp;
11     }
12     head->_next = 0;
13     return q;
14 }

2)栈存储值,然后修改节点值

 1 Node* reverseList2(Node *head) {
 2     if (head == 0) return head;
 3     Node *p = head;
 4     stack<int> s;
 5     while (p) {
 6         s.push(p->_data);
 7         p = p->_next;
 8     }
 9     p = head;
10     while (!s.empty()) {
11         p->_data = s.top();
12         p = p->_next;
13         s.pop();
14     }
15     return head;
16 }

 

判断链表是否有环:快慢指针

 1 bool hasCycle(ListNode *head) {
 2     if (head == nullptr) return false;
 3 
 4     ListNode *fast, *slow;
 5     fast = slow = head;
 6 
 7     do {
 8         fast = fast->_next;
 9         if (fast == nullptr) return false;
10         fast = fast->_next;
11 
12         slow = slow->_next;
13 
14     } while (fast && fast != slow);
15 
16     if (fast == nullptr) return false;
17     return true;
18 }

 

约瑟夫问题:省略

链表-常见题

标签:str   fas   tmp   约瑟夫问题   return   效率   amp   pre   head   

原文地址:https://www.cnblogs.com/hzk-note/p/9589033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!