leetcode_24. Swap Nodes in Pairs C++

来源:互联网 发布:淘宝手链店 编辑:程序博客网 时间:2024/06/16 13:00

     好艰难第一题,不得不说我这蹩脚的coding能力,太久不coding居然连该用->还是.都晕晕乎乎了。  已服我。

   You are here!   Your runtime beats 1.83% of cppsubmissions.       好弱!!!

<span style="font-size:18px;">/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* swapPairs(ListNode* head) {  ListNode *helper;  helper->val = 0;helper->next = head;   ListNode *pre =  helper;while(head && head->next){ListNode *t = head->next->next;                           pre->next = head->next; pre->next->next = head; head->next = t; pre = head; head =t;  } return helper->next;              }};</span>

  • 对链表定义成指针时,对指针操作统一使用->,不管是listNode的变量还是下一个ListNode;
  • 就指针操作经常用到的技巧: 助指针作为表头,链表中比较常用的小技巧,因为这样可以避免处理head的边界情况;




0 0
原创粉丝点击