标签:指针 value head may style 应该 algo pac 不能
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4, you should return the list as2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/** * 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 *res = new ListNode(0); ListNode *p=res; if(head==NULL||head->next==NULL) return head; ListNode *l=head; ListNode *r=l->next; while(l!=NULL&&r!=NULL) { p->next=r; l->next=r->next; r->next=l; p=l; l=p->next; r=l->next; } return res->next; } };
Leetcode swap-nodes-in-pairs(链表 交换相邻节点)
标签:指针 value head may style 应该 algo pac 不能
原文地址:https://www.cnblogs.com/zl1991/p/12799219.html