leetcode - Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->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.
交换相邻的两个结点,若只有奇数个结点,则最后一个结点不做改变
个人思路:
1,从链表头部开始遍历,分别用current指针记录当前结点,next指针记录下一个结点,pre指针记录前一个结点,每次循环都是把next指针指向的结点插入到pre指针之后,然后重新设置一下这3个指针,直到遍历结束
2,注意一下结束条件即可
代码:
1 #include <stddef.h> 2 3 struct ListNode 4 { 5 int val; 6 ListNode *next; 7 ListNode(int x) : val(x), next(NULL) {} 8 }; 9 10 class Solution { 11 public: 12 ListNode *swapPairs(ListNode *head) { 13 if (!head || !head->next) 14 { 15 return head; 16 } 17 18 ListNode dummy(-1); 19 dummy.next = head; 20 ListNode *pre = &dummy; 21 ListNode *current = dummy.next; 22 ListNode *next = NULL; 23 24 while (current && current->next) 25 { 26 next = current->next; 27 28 current->next = next->next; 29 next->next = current; 30 pre->next = next; 31 32 pre = current; 33 current = current->next; 34 } 35 36 return dummy.next; 37 } 38 };
网上基本是这个思路
posted on 2014-09-05 11:05 laihaiteng 阅读(169) 评论(0) 编辑 收藏 举报