leetcode 24. Swap Nodes in Pairs 单向链表操作

来源:互联网 发布:大六壬排盘软件安卓版 编辑:程序博客网 时间:2024/06/05 12:47



Get:

当前指针a指向的地址如果是空的话,a->next无法指向任何地址

将单向链表的奇偶位置互换
代码:

/** * 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 Zero(0);        ListNode *pre=&Zero,*l=NULL,*r=NULL;        ListNode *tmp=pre;        pre->next=head;        while(pre->next && pre->next->next){            l=pre->next;            r=pre->next->next;            pre->next=r;            l->next=r->next;            r->next=l;            pre=l;        }        return tmp->next;    }};


0 0
原创粉丝点击