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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值