leetcode链表题目总结

leetcode中链表题目并不是很多,总共十来道的样子,我个人是觉得,链表题目相对简单,但是有一些问题还是不得不注意的,尤其是在对节点进行插入或删除操作时。

题目示例:

Reverse Nodes in k-Group

 

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

我最开始的提交是这样的:

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if ((head == NULL) || ( k < 2))
            return head;
            
        ListNode *phead = new ListNode(0); 
        ListNode *ptemp = new ListNode(0);
        ListNode *detection, *operate, *ptail = phead, *temp, *ptemptail;
        detection = head;
        operate = head;
        
        while (detection != NULL){
            int flag = 0;
            for (int i = 0; i < k; i++){  //detective if the left-out nodes more than k
                if (detection == NULL){
                    flag = 1;
                    break;
                }else{
                    detection = detection->next;
                }
            }
            if (flag == 1){               //if less than k 
                ptail->next = operate;
                break;
            }
            ptemp->next = NULL;               //if not less than k
            for (int i = 0; i < k; i++){
                temp = ptemp->next;
                ptemp->next = operate;//XXXXXX
                ptemp->next->next = temp;//XXXXXXX
                operate = operate->next;//XXXXXXX
                if (i == 0)
                    ptemptail = ptemp->next;
            }
            ptail->next = ptemp->next;
            ptail = ptemptail;
            ptail->next = operate;
        }
        return phead->next;
    }
};


总是提交报错,找了半天也没发现什么错误。而问题恰恰就出在标xxxx的这部分代码。

所以,做链表题,一定要时刻警醒注意,指针和节点本身有却别,脑子里头要想明白自己改的到底是什么。

上面只需要将

       ptemp->next->next = temp;
       operate = operate->next;
调换下位置就可以了。

小细节,成就大问题。come on!

你可能感兴趣的:(leetcode)